Freigeben über


LINQ to non-enumerable?

So I was reading Wes' latest post about Monad's a while back (which incidentally is well worth a read, it is the first good explanation of Monad's I've seen that uses a language I am comfortable with in it's examples, namely C#).

Well one thing Wes kind of brushes over is the fact that he ends up using a LINQ query against something that DOES NOT implement IEnumerable.

I for one didn't know you could do that.

It turns out that to be used as LINQ datasource a variable either needs to implement IEnumerable, IEnumerable<T> or have an appropriate SelectMany(...) method. 

The Maybe<T> class that Wes introduces in his Monad walk thru, is an example of a datasource/class that doesn't implement IEnumerable<T> but instead has the right SelectMany(...) method:

            var z = from x in 5.ToMaybe()
                    from y in Maybe<int>.Nothing
                    select x / y;

I'll leave it to you to ponder the possibilities...

Comments

  • Anonymous
    January 15, 2008
    Actually, it just needs to implement methods that meet the requirements of query translation (see 7.15.3 of the C# 3.0 spec).  What you do with those is your own business :)It just so happens that we shipped implementations for IEnumerable<T> and IQueryable<T> (which also implements IEnumerable<T>), and all our examples happen to themselves be enumerable.You could, for instances, have an IFooable<T>, which doesn't implement any of this, but has implementations of the standard query operators which do their own thing, and then call some magic method which returns something useful, but having said magic be an IEnumerable<T> implementation is more useful.
  • Anonymous
    January 15, 2008
    PingBack from http://msdn.blogsforu.com/msdn/?p=3778
  • Anonymous
    January 16, 2008
    Duck typing.