Linq for Predicate Builder Objects

What is the best way to execute a conditional query using linq for objects (not linq for sql).

I am currently using the Predicate builder found here http://www.albahari.com/nutshell/predicatebuilder.aspx and passing the compiled predicate to IEnumerable.Where, and it seems to work fine.

Example code that I want to solve:

for example, I have it

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(); 
+7
c # linq-to-objects
source share
1 answer

Just change the PredicateBuilder to use delegates instead of expression trees and use lambdas to create the results:

 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); } } 
+14
source share

All Articles