It's possible to use LINQ queries to get data from an IEnumerable<T>. But for an IEnumerable, you can't use LINQ. If you write this LINQ query for an IEnumerable:
IEnumerable ienumerable = new int[] { 1, 5, 6, 7, 8, 11, 10, 134, 90 };
var integer = from i in ienumerable where i > 10 select i;
Then, you get this error: Could not find an implementation of the query pattern for source type 'System.Collections.IEnumerable'. 'Where' not found. Consider explicitly specifying the type of the range variable 'i'.
In this tip, I tell you how to cast an IEnumerable to an IEnumerable<T>.
Cast an IEnumerable to an IEnumerable<T>
To cast an IEnumerable to an IEnumerable<T>, you can use this code:
IEnumerable ienumerable = new int[] { 1, 5, 6, 7, 8, 11, 10, 134, 90 };
IEnumerable casted = ienumerable.Cast<int>(); // change 'int' into the type of the elements in your IEnumerable
...
...
IEnumerable ienumerable = new object[] { 1, 5, 6, 7, 8, 11, 10, 134, 90, "test" };
IEnumerable<int> allIntegers = ienumerable.OfType<int>(); // change 'int' in the type of the elements you want to get from the IEnumerable
Read more: Codeproject
QR:
0 comments:
Post a Comment