linq – Jay R. Wren – lazy dawg evarlast http://jrwren.wrenfam.com/blog babblings of a computer loving fool Wed, 15 Feb 2017 02:57:57 +0000 en-US hourly 1 https://wordpress.org/?v=4.7.2 LINQ Abuse with the C# 4 dynamic type http://jrwren.wrenfam.com/blog/2010/03/04/linq-abuse-with-the-c-4-dynamic-type/ http://jrwren.wrenfam.com/blog/2010/03/04/linq-abuse-with-the-c-4-dynamic-type/#comments Fri, 05 Mar 2010 03:13:48 +0000 http://jrwren.wrenfam.com/blog/2010/03/04/linq-abuse-with-the-c-4-dynamic-type/ Continue reading "LINQ Abuse with the C# 4 dynamic type"]]> With C# 4 adding some support for dynamic typing one of the first thing that I wanted to do is use it with LINQ.

I want to do this:

dynamic x;
var h = from y in x where y == 1 select y.something;

But I get error messages on both where and select that says

Query expressions over source type ‘dynamic’ or with a join sequence of ‘dynamic’ are not allowed

Major bummer.

But surely there is something I can do. 🙂

*the title of this post starts with LINQ abuse… please don’t comment about how stupid and evil this is. I know it. Instead, consider this an exercise in getting to know C# a little better.

The dynamic type is just sugar for the object type and some attributes to which the compiler pays attention.

Lets use object…

object things = new[] { 0,1,2,3,4,5,6,7, };
var whatIwant = from thing in things
                            where thing % 2 == 0
                            select thing;
// or if you like longhand:
var wiw = things.Where(thing => thing%2 == 0).Select(thing => thing);

How does this compile? Well, by making Where and Select resolve to extension methods on object instead of extension methods on IEnumerable<T> (which is what people USUALLY think of when they think LINQ).

public static IEnumerable<dynamic> Select(this object source, Func<dynamic, dynamic> map)
{
    foreach (dynamic item in source as dynamic)
    {
        yield return map(item);
    }
}
public static IEnumerable<dynamic> Where(this object source, Func<dynamic, dynamic> predicate)
{
    foreach (dynamic item in source as dynamic)
    {
        if (predicate(item))
            yield return item;
    }
}

Extension methods on object, then cast to dynamic (extension methods aren’t allowed on dynamic).

It should be short work to fill out whatever LINQ methods are necessary to make whatever LINQ expressions you wish work against dynamic (object) and now you can use LINQ with a source that is typed dynamic.

]]>
http://jrwren.wrenfam.com/blog/2010/03/04/linq-abuse-with-the-c-4-dynamic-type/feed/ 4