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>, notIEnumerable. For example, see theWhere<T>signature:To mitigate this issue, the LINQ
Cast<T>extension method turns anIEnumerableinto anIEnumerable<T>that can then be used with the normal LINQ functions.In the example below, you can’t do
e.Where(...), but you canCastit and then useWhere.Unfortunately, this needs to be used a lot when dealing with pre-generics APIs in the .NET BCL.