Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable<T>.Contains with predicate

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?

like image 831
abatishchev Avatar asked Jul 25 '10 10:07

abatishchev


People also ask

How do I know if IEnumerable has an item?

enumerable. Any() is the cleanest way to check if there are any items in the list.

How use contains in LINQ query?

To check for an element in a string, use the Contains() method. The following is our string array. string[] arr = { "Java", "C++", "Python"}; Now, use Contains() method to find a specific string in the string array.

What is any () in C#?

The Any method checks whether any of the element in a sequence satisfy a specific condition or not. If any element satisfy the condition, true is returned.

How do you use LINQ to check if a list of strings contains any string in a list?

Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .


1 Answers

.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.

like image 165
Marc Gravell Avatar answered Sep 30 '22 16:09

Marc Gravell