6

I have a list of predicates

public List<Func<Album, bool>> Predicates { get; set; }

I'd like to check if a list contains specific predicate.

What I do is this :

bool check = Predicates.Contains(x=>x.AlbumName == "Winter");

But this always returns false even though there is such a predicate in the list. I assume it is because predicates are anonymous methods and each is kind of unique, but still is it possible to compare them somehow?

2
  • Predicates.Any() "might" help, if it is for testing purposes :-)
    – Sruti
    Dec 9, 2014 at 11:58
  • @Sruti Expand on that "might". How Predicates.Any is going to help here? Dec 9, 2014 at 12:06

4 Answers 4

5

I'm afraid the answer is basically "no". If you had expression trees instead of delegates then you could probably compare those with effort, but basically you've got references to separate methods. You'd need to inspect the IL inside the methods to compare whether or not they're the same.

Of course if you have a set of objects on which the predicates operate, you could find out whether you have any predicates which matches the same subset as your "target" predicate, but that's not the same as testing whether the predicate is actually the same.

1

Predicate comparison is perfectly possible. What you are doing wrong is you are using lambda expressions, basically declaring new methods for each predicate (AND for their comparison)! :)

Instead of lambdas, use normal functions.

For example, declare: bool AlbumNameFilter(Album album) {return album.Name == "Winter";}

You will be able to add AlbumNameFilter to Predicates list and Find it later:

Predicates.Contains(AlbumnameFilter);
0

Switch to Expression< Func< Album, bool>> list and create custom comparer

0

You can use Dictionary instead of List. Then you can compare the different Predicates by whatever you assign as a Key.

Dictionary<(YourKey), Predicate<Album>> predicates = new Dictionary<(YourKey), Predicate<Album>>;

....

if (!predicates.ContainsKey((YourKey)))
{
    predicates.Add((YourKey), x => x.AlbumName == "Winter")
}
else
{
    predicates.Remove((YourKey));
}

Then to use the Predicate you just access the Dictionary Value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.