How to make a SELECT LINQ Query variable position

Is it possible to make LINQ SELECT more flexible without working with properties, but with a column name? Maybe an example will help ... I'm trying to do the following (pseudocode):

From x In Entities Where ... Select("ID", "Value" , "Date") 

but depending on certain options, I would like to get the result in a different order

 From x In Entities Where ... Select("Value", "Date", "ID" ) 

Or another number of SELECT results

 From x In Entities Where ... Select("Value") 

Any help to make this as dynamic as possible would be AWESOME! Tnx

0
source share
2 answers

Maybe this will help you

 from x In Entities where ... select new { Value = x["Value"], Date = x["Date"], ID = x["ID"] } 
+1
source

As I said in my comment (handles routines such as Type.Name, but not several fields) I allowed a fun multi-user 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); } } 

Using:

 var names = DataContext.Customers.Select("Name").Cast<string>().ToList(); 
0
source

All Articles