I am trying to build a LINQ query at runtime so that only certain properties are selected. I have thought of something along the lines of being able to build a query by appending additional .Select() calls to my query or using the dynamic LINQ extensions to pass a string of columns (would like to stay away from a string built query). However my current attempts at finding a solution have not worked.
+1
A:
You need to look into linq expressions. Here is a small example that should work for selecting a single property, selecting more than that becomes more difficult, but is generally doable if you define a type with the properties you are selecting (eg. don't use anonymous types in the queries you are generating).
using System.Linq.Expressions;
...
IQueryable<T> query = someQuery;
Expression expression = query.Expression;
ParameterExpression obj = Expression.Parameter(query.ElementType, "obj");
MemberExpression property = Expression.PropertyOrField(obj, propertyName);
Expression<Func<T,bool>> lambda = Expression.Lambda<Func<T,bool>>(property, obj);
query = query.Where(lambda);
At least, thats the general idea
LorenVS
2009-08-19 14:44:35
You might be right that it is time that I dive into how LINQ Expression trees work.
jwarzech
2009-08-19 15:08:24
A:
As Justin commented, your difficulty will be finding a type to return. The advantage of LINQ is that you have strongly-typed entities to work with. If those don't work to your advantage, or you find yourself doing a lot of work against the grain, there's probably a better solution out there.
dahlbyk
2009-08-19 17:12:54