Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ for an object that only has GetEnumerator()

Tags:

.net

linq

Can you use LINQ in an object that exposes only Add(), Remove(), Count(), Item() and GetEnumerator() from System.Collections.IEnumerator?

like image 268
Salvador Avatar asked Sep 12 '09 18:09

Salvador


People also ask

What is GetEnumerator()?

The C# GetEnumerator() method is used to convert string object into char enumerator. It returns instance of CharEnumerator. So, you can iterate string through loop.

Can you use LINQ on IEnumerable?

All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!

What collections can LINQ be used with?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.


1 Answers

The existing Linq extension methods work on objects that implement IEnumerable<T>. I assume your object implements the non-generic IEnumerable interface. In that case you can use the Cast<T> extension method to get a generic IEnumerable<T> wrapper. For instance, if the elements are of type int :

var wrapper = myObject.Cast<int>(); 

You can now use Linq on the wrapper

like image 127
Thomas Levesque Avatar answered Oct 08 '22 00:10

Thomas Levesque