Is it possible to make the LINQ SELECT more flexible by not working with properties but with the column name? Maybe an example will help..I\'m trying to do the following (pseudo
Like I said in my comment (handles subproperties, like Type.Name, but not multiple fields) I let the fun to make the multi field version ;)
public static class DynamicLinkExtensions
{
public static IEnumerable<dynamic> Select<T>(this IQueryable<T> source, string memberAccess)
{
var propNames = memberAccess.Split('.');
var type = typeof(T);
var props = new List<PropertyInfo>();
foreach (var propName in propNames)
{
var prop = type.GetProperty(propName);
props.Add(prop);
type = prop.PropertyType;
}
return source.Select(props.ToArray());
}
public static IEnumerable<dynamic> Select<T>(this IQueryable<T> source, PropertyInfo[] props)
{
var parameter = Expression.Parameter(typeof(T));
var member = Expression.MakeMemberAccess(parameter, (MemberInfo)props.First());
for (var i = 1; i < props.Length; i++)
{
member = Expression.MakeMemberAccess(member, (MemberInfo)props[i]);
}
Expression<Func<T, object>> expression = Expression.Lambda<Func<T, object>>(member, new[] { parameter });
return source.Select(expression);
}
}
Usage:
var names = DataContext.Customers.Select("Name").Cast<string>().ToList();
Maybe this will help you
from x In Entities
where ... select new {
Value = x["Value"],
Date = x["Date"],
ID = x["ID"]
}