How to make the position of a LINQ Query SELECT variable

前端 未结 2 597
一向
一向 2021-01-26 04:45

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

相关标签:
2条回答
  • 2021-01-26 05:41

    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();
    
    0 讨论(0)
  • 2021-01-26 05:50

    Maybe this will help you

    from x In Entities
    where ... select new {
      Value = x["Value"],
      Date = x["Date"],
      ID = x["ID"]
    }
    
    0 讨论(0)
提交回复
热议问题