IEnumerable<T>.Contains with predicate

24,324

Solution 1

.Any(predicate)

sounds like what you want; returns bool, returning true as soon as a match is found, else false. There is also:

.All(predicate)

which behaves in a similar way, returning false as soon as a non-match is found, else true.

Solution 2

You can use Any(predicate). It will return true or false depending if the predicate exists in a certain collection.

Solution 3

Have a look at the IEnumerable<T>.Any extension.

Share:
24,324
abatishchev
Author by

abatishchev

This is my GUID. There are many like it but this one is mine. My GUID is my best friend. It is my life. I must master it as I must master my life. Without me, my GUID is useless. Without my GUID I am useless.

Updated on June 04, 2020

Comments

  • abatishchev
    abatishchev almost 4 years

    I need just to clarify that given collection contains an element.

    I can do that via collection.Count(foo => foo.Bar == "Bar") > 0) but it will do the unnecessary job - iterate the whole collection while I need to stop on the first occurrence.

    But I want to try to use Contains() with a predicate, e.g. foo => foo.Bar == "Bar".

    Currently IEnumerable<T>.Contains has two signatures:

    • IEnumerable<T>.Contains(T)

    • IEnumerable<T>.Contains(T, IEqualityComparer<T>)

    So I have to specify some variable to check:

    var collection = new List<Foo>() { foo, bar };
    collection.Contains(foo);
    

    or write my custom IEqualityComparer<Foo> which will be used against my collection:

    class FooComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo f1, Foo f2)
        {
            return (f1.Bar == f2.Bar); // my predicate
        }
    
        public int GetHashCode(Foo f)
        {
            return f.GetHashCode();
        }   
    }
    

    So are there any other methods to use predicate?