Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we have a "Contains" method in IEnumerable

Tags:

c#

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?

like image 924
Bohn Avatar asked Dec 07 '12 16:12

Bohn


People also ask

How do I know if IEnumerable has an item?

Use Any() Instead of Count() To See if an IEnumerable Has Any Objects. An IEnumerable is an implementation that supports simple iteration using an enumerator.

What is IEnumerable method in C#?

IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.

Can we convert IEnumerable to List C#?

In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();

How do I get an item from IEnumerable?

We can get first item values from IEnumerable list by using First() property or loop through the list to get respective element. IEnumerable list is a base for all collections and its having ability to loop through the collection by using current property, MoveNext and Reset methods in c#, vb.net.


1 Answers

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 :)

like image 59
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet