How to access items in a dynamic list?

大憨熊 提交于 2020-01-11 10:54:09

问题


I am trying to figure out how to enumerate the results from a dynamic LINQ .Select(string selectors) in .NET 4.5. The dynamic linq comes from the System.Linq.Dynamic namespace.

Edit: I am also including System.Linq.

I have a method that looks like this:

    public void SetAaData(List<T> data, List<string> fields)
    {
        if (data == null || data.Count == 0)
        {
            return;
        }
        var dynamicObject = data.AsQueryable().Select("new (" + string.Join(", ", fields) + ")");
        _aaData = dynamicObject;
    }

If I step through the code, I can examine dynamicObject and enumerate it to view the results (which are correct). The problem is that I am now trying to get my unit test to pass for this, and I've been unable to access anything in dynamicObject. The _aaData field is defined as the type dynamic.

In my test method, I tried this:

        var hasDynamicProperties = new MyClass<MyType>();
        dgr.SetAaData(data, fields); // data is a List<MyType>
        Assert.IsTrue(hasDynamicProperties.AaData.Count > 0);

When I run this test, I get the following error:

MyTestingClass threw exception: 
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Linq.EnumerableQuery<DynamicClass1>' does not contain a definition for 'Count'

So, I tried to cast it to a list:

Assert.IsTrue(dgr.AaData.ToList().Count() > 0);

Which resulted in the following error:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Linq.EnumerableQuery<DynamicClass1>' does not contain a definition for 'ToList'

So, then I looked up System.Linq.EnumerableQuery<T> here: http://msdn.microsoft.com/en-us/library/cc190116.aspx. I see all that .Count() is supposed to be a valid extension method, but it does not work when I try it. In fact, none of the methods from that page work when I try them.

What am I doing wrong?


回答1:


Extension methods can not be applied to dynamic objects as if they were member methods.

Count() is an extension method defined in System.Linq.Queryable, you can call it directly on your dynamic object:

Assert.IsTrue(Queryable.Count(hasDynamicProperties.AaData) > 0)


来源:https://stackoverflow.com/questions/16843572/how-to-access-items-in-a-dynamic-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!