using System;using System.Collections.Generic;using System.linq;using System.linq.Expressions;namespace ExpressionTest{ class Program { static voID Main(string[] args) { /* Expression */ Expression<Func<int,bool>> Expression = item => item % 2 == 0; /* List */ IList<int> items = new List<int>(); for (int i = 0; i < 10; i++) { items.Add(i); } IEnumerable<int> evennumbers = items.Where(Expression.Compile()); foreach (int number in evennumbers) { Console.Writeline(number.ToString()); } /* Wrappers List */ // How to apply Expression to the porpery 'Number'? IList<Wrapper> wrappers = new List<Wrapper>(); for (int i = 0; i < 10; i++) { wrappers.Add(new Wrapper { Number = i }); } IEnumerable<int> evenWrappednumbers = ????; foreach (Wrapper wrappednumber in evenWrappednumbers) { Console.Writeline(wrappednumber.ToString()); } } } public class Wrapper { public int Number; }}解决方法 这应该做的伎俩:
Func<int,bool> predicate = Expression.Compile();IEnumerable<Wrapper> evenWrappednumbers = wrappers.Where(w => predicate(w.Number));
或者如果你想要一个IEnumerable< int>
Func<int,bool> predicate = Expression.Compile();IEnumerable<int> evenWrappednumbers = wrappers.Where(w => predicate(w.Number)).Select(w => w.Number);
编辑:自从了解NHibernate正在使用中,这是另一种可能的解决方案.请记住,我不使用NHibernate并且对表达式树的经验有限.但无论如何,这应该允许NHibernate将表达式树解析为sql.
首先在静态类中定义一个扩展方法,如下所示:
public static Iqueryable<T> Where<T,TProperty>(this Iqueryable<T> source,Expression<Func<T,TProperty>> propertySelector,Expression<Func<TProperty,bool>> predicate) { MemberExpression member = propertySelector.Body as MemberExpression; if (member == null) throw new ArgumentException("Must be a property selector","propertySelector"); string propertyname = member.Member.name; // The input type ParameterExpression propertyParameter = Expression.Parameter(typeof(T)); // The property on that type MemberExpression itemProperty = Expression.Property(propertyParameter,propertyname); // Invoke the specifIEd predicate with the property from the input type InvocationExpression invokeExpression = Expression.Invoke(predicate,itemProperty); // The lambda Expression for use with linq Expression<Func<T,bool>> finalExpression = Expression.Lambda<Func<T,bool>>(invokeExpression,propertyParameter); return source.Where(finalExpression); }
然后可以像这样使用这种扩展方法:
IEnumerable<Wrapper> evenWrappednumbers = wrappers.Where(w => w.Number,Expression);
正如我所说,我没有NHibernate的经验,但希望它能够解析这个表达式树并将其转换为sql.
总结以上是内存溢出为你收集整理的c# – 将对象的linq表达式应用于该对象是项目属性的项目列表(Wrapper)全部内容,希望文章能够帮你解决c# – 将对象的linq表达式应用于该对象是项目属性的项目列表(Wrapper)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)