views:

28

answers:

1

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?

+2  A: 

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.

Chris Schmich
Oh, I knew that it is something obvious ;-) Thank you.
zerkms
Yes, in some unknown reason I thought that LINQ automatically does cast for non-generic collections.
zerkms
@zerkms Yeah I get surprised every time IntelliSense pops-up without the extension methods. Good thing they included `Cast` in the shipping libraries!
Chris Schmich