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?
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.
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.
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();
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With