Examples for "(Not) interesting observation on LINQ"

After the post (Not) interesting observation on LINQ was out Michal Blaha asked me to show some example to show what I’m talking about. :)

OK, here it is. This example shows the first observation from second paragraph (yep, it’s second ;) ). I’m using only Where, for the sake of simplicity.

class Program
{
    static void Main(string[] args)
    {
        Class1 a = new Class1();
        var q = from x in a
                where x.Foo > 20
                select new { Bar = x.Foo };
    }
}

class Class1
{
    public int Foo { get; set; }

    public IEnumerable<Class1> Where(Func<Class1, bool> predicate)
    {
        return new[] { this };
    }
}

No IQueryable, no querying provider stuff, etc. Compiles without problems, and runs without complaining. No magic, right?

Now the third (last) paragraph.

class Program
{
    static void Main(string[] args)
    {
        Class1 a = new Class1();
        var q = from x in a
                where x.Foo > 20
                select new { Bar = x.Bar };
    }
}

class Class1
{
    public int Foo { get; set; }

    public IEnumerable<Class2> Where(Func<Class1, bool> predicate)
    {
        return new[] { new Class2() };
    }
}

class Class2
{
    public int Bar { get; set; }
}

The example is magically returning from Where IEnumerable of other class. :) Doing this with couple of standard LINQ operators may confuse your colleagues well. You can also check the “LINQ to Simpsons” from Bart de Smet to see comprehensive confusing.

  • Twitter
  • Facebook
  • Share/Bookmark
This entry was posted in .* and tagged . Bookmark the permalink.

One Response to Examples for "(Not) interesting observation on LINQ"

  1. And you can do even more challenging things such as queries over events :-) . See my Reactive LINQ project: http://tomasp.net/blog/reactive-iv-reactivegame.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>