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?
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