I'm trying to implement PredicateBuilder and created a simple test.
I'm currently using PredicateBuilderDelegate because I'm testing against a List
Problem is when I run the test I does not 'filter' the records and collections contains the same elements and I can't see why this is happening.
FakeEntity Class:
public class FakeEntity {
public int Id { get; set; }
public string Name { get; set; }
public bool IsDeleted { get; set; }
public static Func<FakeEntity, bool> NotDeleted() {
var predicate = PredicateBuilderDelegate.True<FakeEntity>();
predicate.And(e => !e.IsDeleted);
return predicate;
}
}
Test:
[TestClass]
public class PredicateBuilderTest {
[TestMethod]
public void Test() {
var collection = new List<FakeEntity>() { new FakeEntity { IsDeleted = true }, new FakeEntity { IsDeleted = false } };
var result = collection.Where(FakeEntity.NotDeleted()).ToList();
CollectionAssert.AreNotEquivalent(collection, result); // FAIL!
Assert.IsTrue(result.Count() == 1); // FAIL !!
}
}
PredicateBuilderDelegate:
public static class PredicateBuilderDelegate {
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);
}
}