Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LINQ work with IEnumerable?

I have a class that implements IEnumerable, but doesn't implement IEnumerable<T>. I can't change this class, and I can't use another class instead of it. As I've understood from MSDN LINQ can be used if class implements IEnumerable<T>. I've tried using instance.ToQueryable(), but it still doesn't enable LINQ methods. I know for sure that this class can contain instances of only one type, so the class could implement IEnumerable<T>, but it just doesn't. So what can I do to query this class using LINQ expressions?

like image 208
Bogdan Verbenets Avatar asked Oct 13 '11 16:10

Bogdan Verbenets


People also ask

What is LINQ IEnumerable?

IEnumerable exists in the System. Collections namespace. IEnumerable is suitable for querying data from in-memory collections like List, Array and so on. While querying data from the database, IEnumerable executes "select query" on the server-side, loads data in-memory on the client-side and then filters the data.

When should I use IQueryable and IEnumerable using LINQ?

In LINQ to query data from database and collections, we use IEnumerable and IQueryable for data manipulation. IEnumerable is inherited by IQueryable, Hence IQueryable has all the features of IEnumerable and except this, it has its own features. Both have its own importance to query data and data manipulation.

Does IQueryable implement IEnumerable?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed.

Which interface must be implemented by a class to use LINQ?

Despite common perception, you do not have to implement the IEnumerable interface for your class to support LINQ. However, implementing IEnumerable will automatically get you the entire set of LINQ methods on the Enumerable class almost for free -- you only have to implement GetEnumerator and an IEnumerator class.


2 Answers

You can use Cast<T>() or OfType<T> to get a generic version of an IEnumerable that fully supports LINQ.

Eg.

IEnumerable objects = ...; IEnumerable<string> strings = objects.Cast<string>(); 

Or if you don't know what type it contains you can always do:

IEnumerable<object> e = objects.Cast<object>(); 

If your non-generic IEnumerable contains objects of various types and you are only interested in eg. the strings you can do:

IEnumerable<string> strings = objects.OfType<string>(); 
like image 186
DeCaf Avatar answered Sep 28 '22 14:09

DeCaf


Yes it can. You just need to use the Cast<T> function to get it converted to a typed IEnumerable<T>. For example:

IEnumerable e = ...; IEnumerable<object> e2 = e.Cast<object>(); 

Now e2 is an IEnumerable<T> and can work with all LINQ functions.

like image 31
JaredPar Avatar answered Sep 28 '22 14:09

JaredPar