Bohn
Bohn

Reputation: 26929

Do we have a "Contains" method in IEnumerable

I have a class in my code that is already deriving from IEnumerable. I was wondering if there is a way that I can use a "Contains" method on its instnaces to look for a something in that list?

Upvotes: 23

Views: 49089

Answers (3)

Smagin Alexey
Smagin Alexey

Reputation: 345

public static bool Contains<T>(this IEnumerable source, T value)
    {
        foreach (var i in source)
        {
            if (Equals(i, value))
                return true;
        }
        return false;
    }

If you want, you can add custom comparer as parameter ti extension method Contains

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504172

Do you really implement the non-generic IEnumerable, or the generic IEnumerable<T>? If you can possibly implement the generic one, your life will become a lot simpler - as then you can use LINQ to Objects, which does indeed have a Contains extension method.

Otherwise, you could potentially convert from the non-generic to generic using Cast or OfType, e.g.

bool found = nonGeneric.Cast<TargetType>().Contains(targetItem);

It would be nicer if you just implemented the generic interface to start with though :)

Upvotes: 29

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

No, there's no such method in the IEnumerable<T> interface. There's an extension method though that you could use.

using System.Linq;

and then:

IEnumerable<string> foos = new[] { "foo", "bar", "baz" };
bool IsThereABar = foos.Contains("bar");

Upvotes: 30

Related Questions