Tutorial :LINQ - How to Construct Query When the Column Name is not known until Runtime?



Question:

Given:

string metadata.XAxisColumn -- contains a column name (e.g., "Date")  string metadata.YAxisColumn -- contains another columnname (e.g., "Close")  

When I know the names of the columns up front, of course I can do:

var query = from record in myView       where record.Date >= startDate && record.Date <= endDate      select record.Close  

However, the column names are not known until runtime. They're in metadata.XAxisColumn and metadata.YAxisColumn.

What is the correct way to construct a query that works like this:

var query = from record in myView       where record.[metadata.XAxisColumn] >= startDate && record.[metadata.XAxisColumn] <= endDate      select record.[metadata.YAxisColumn]  


Solution:1

You use either ESQL/QueryBuilder (built in to EF) or Microsoft Dynamic Query (a.k.a. Dynamic LINQ -- free via VS Code Gallery).


Solution:2

You could derive from the type of 'record' objects, and add a new property:

public class MyRecord : RecordBase  {      public XAxis      {          get          {              switch (metadata.XAxisColumn)              {                  // for example only; this code will not compile because it depends what kind of object RecordBase is :)              case X:                  return this.X;              case Y:                  return this.Y;                      }          }      }  }  

Hope that helps!


Solution:3

You could use Dynamic LINQ for those queries


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »