Native Dynamic Linq (C #)

Can I use a keyword dynamic

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 practical right now.

The easiest way to illustrate my point is with 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 for each request: Throws a compiler error -

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

+3


source to share


1 answer


Replace the T declaration in Bar to use 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
    }
}

      

+2


source







All Articles