kwi*_*iri 8 c# linq-to-objects
使用linq到对象(不是linq到sql)进行条件查询的最佳方法是什么.
目前我正在使用http://www.albahari.com/nutshell/predicatebuilder.aspx中的Predicate构建器 ,并将已编译的谓词传递给IEnumerable.Where,它似乎工作得很好.
我要解决的示例代码:
我有这个
string keyword1 = "Test1";
string keyword2 = "Test3";
IEnumerable<TestObject> tests = new List<TestObject>()
{
new TestObject() {Name1 = "Test1", Name2 = "Test1"},
new TestObject() {Name1 = "Test2", Name2 = "Test2"},
new TestObject() {Name1 = "Test3", Name2 = "Test3"},
};
if (!String.IsNullOrEmpty(keyword1) && String.IsNullOrEmpty(keyword2))
tests = tests.Where(e => e.Name1.Contains(keyword1));
else if (!String.IsNullOrEmpty(keyword2) && !String.IsNullOrEmpty(keyword1))
tests = tests.Where(e => e.Name2.Contains(keyword2) || e.Name1.Contains(keyword1));
return tests.ToList();
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 14
只需更改PredicateBuilder为使用委托而不是表达式树并使用lambdas来构建结果:
public static class DelegatePredicateBuilder
{
public static Func<T, bool> True<T>() { return f => true; }
public static Func<T, bool> False<T>() { return f => false; }
public static Func<T, bool> Or<T>(this Func<T, bool> expr1,
Func<T, bool> expr2)
{
return t => expr1(t) || expr2(t);
}
public static Func<T, bool> And<T>(this Func<T, bool> expr1,
Func<T, bool> expr2)
{
return t => expr1(t) && expr2(t);
}
}
Run Code Online (Sandbox Code Playgroud)