Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requirements for collection class to be used with LINQ

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?

like image 234
zerkms Avatar asked Dec 17 '25 22:12

zerkms


1 Answers

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.

like image 129
Chris Schmich Avatar answered Dec 19 '25 16:12

Chris Schmich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!