I always thought that enough requirement that class should satisfy to be able to use Where() with it is to implement IEnumerable.
But today a friend of mine asked me a question, why he cannot apply Where() to the object of SPUserCollection class (it is from Sharepoint). Since this class is derived from SPBaseCollection which implements IEnumerable - I expected everything should be fine. But it is not.
Any ideas, why?
The LINQ extension methods are defined over IEnumerable<T>, not IEnumerable. For example, see the Where<T> signature:
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
To mitigate this issue, the LINQ Cast<T> extension method turns an IEnumerable into an IEnumerable<T> that can then be used with the normal LINQ functions.
In the example below, you can't do e.Where(...), but you can Cast it and then use Where.
int[] xs = new[] { 1, 2, 3, 4 };
IEnumerable e = xs;
var odds = e.Cast<int>().Where(x => x % 2 == 1);
Unfortunately, this needs to be used a lot when dealing with pre-generics APIs in the .NET BCL.
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