3
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

Flat Eric
  • 7,971
  • 9
  • 36
  • 45
  • Yes, this is possible. You need to use reflection to build an expression tree dynamically. Here's an example of building an expression tree dynamically http://msdn.microsoft.com/en-us/library/bb882637.aspx – Steve Lillis Dec 24 '14 at 09:47
  • I think you should take a look at http://stackoverflow.com/questions/606104/how-to-create-linq-expression-tree-with-anonymous-type-in-it – John Dec 24 '14 at 10:22

1 Answers1

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 });
    }
Catwood
  • 157
  • 7
  • I dont know return type (can be anonymous type) and the fildName can be multiply the best result http://stackoverflow.com/questions/16516971/linq-dynamic-select but return type must be object or anonymous type this example not work – Ahmet Günaydın Dec 24 '14 at 11:21
  • @AhmetGünaydın The return type would be the list you are querying. Could you loop through the multiple parameters adding a new select to an IQueryable object? – Catwood Dec 24 '14 at 11:24