1

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);
    }
}
Bart Calixto
  • 19,210
  • 11
  • 78
  • 114

1 Answers1

3

The And method returns a new predicate. It does not mutate the predicate to change it. (Delegates are immutable after all.) You're ignoring the return value of the method.

Servy
  • 202,030
  • 26
  • 332
  • 449