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?
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.
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.
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.
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.
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>();
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.
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