dynamically build select clause linq

孤街醉人 提交于 2021-01-27 19:22:28

问题


class someClass
{ 
    public int Id { get; set; }
    public string Name{ get; set; }
    ...
    public string someProperty { get; set; }          
}

Expression<Func<someClass, object>> selector = null;
selector = k => new { k.Id ,k.Name };
var serult = myData.Select(selector);

// .Select(p=> new {p.Name , p.Id}) etc.

This sample code is working But;

Expression<Func<someClass, ???>> createSelector(string[] fields)
{
    ...
    ....
    return ...
} 

Expression<Func<someClass, ???>> selector = createSelector({"Name","Id"});

Is this possible? This method when running create dynamic selector


回答1:


This can be used to create the expression you need.

    public static Expression<Func<T, TReturn>> CreateSelector<T, TReturn>(string fieldName)
        where T : class
        where TReturn : class
    {
        ParameterExpression p = Expression.Parameter(typeof(T), "t");
        Expression body = Expression.Property(p, fieldName);
        Expression conversion = Expression.Convert(body, typeof(object));
        return Expression.Lambda<Func<T, TReturn>>(conversion, new ParameterExpression[] { p });
    }


来源:https://stackoverflow.com/questions/27634801/dynamically-build-select-clause-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!