开发者

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

Given:

string metadata.XAxisColumn -- contains a column name (e.g., "Date")
string metadata.YAxisColumn -- contains another col开发者_StackOverflow社区umnname (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]


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


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!


You could use Dynamic LINQ for those queries

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜