3

Is it possible to utilise the dynamic keyword in c# 5.0 (.Net 4.5) to create a dynamic LINQ query?

I know this is possible using third party libraries, but this is not viable right now.

The easiest way to illustrate my point is through an example:

    class test
    {
        public int i { get; set; }
    }

    void Foo()
    {
        var collection = new[] { new test() { i = 1 }, new test() { i = 2 } };
        Bar(collection);
    }

    void Bar<T>(IEnumerable<T> collection)
    {
        //this works
        foreach (dynamic item in collection)
            if (item.i == 2)
            {
                //do something
            }

        //this does not - although this is what id like to use
        foreach (dynamic item in collection.Where(a => a.i == 2))
        {
            //do something
        }
    }

Edit per request: Produces a compiler error -

'T' does not contain a definition for 'i' and no extension method 'i' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

4

1 回答 1

2

替换 T in Bar 声明以使用 dynamic :

void Bar(IEnumerable<dynamic> collection)
{
    //this works
    foreach (dynamic item in collection)
        if (item.i == 2)
        {
            //do something
        }

    //this does compile
    foreach (dynamic item in collection.Where(a => a.i == 2))
    {
        //do something
    }
}
于 2013-01-31T10:48:36.403 回答