我试图找出如何从一个动态的LINQ 。选择(字符串选择器)
枚举结果.NET 4.5。动态LINQ来自 System.Linq.Dynamic
命名空间。
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.
编辑:我还包括 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;
}
如果我在code步骤,我可以检查 dynamicObject
和枚举它来查看结果(这是正确的)。问题是,我现在试图让我的单元测试通过了这一点,我已经无法访问任何东西dynamicObject。该 _aaData 字段定义为类型
动态
。
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'
所以,后来我抬头一看 System.Linq.EnumerableQuery&LT; T&GT;
此处的 http://msdn.microsoft.com/en-us/library/cc190116.aspx 。我看到所有的 .Count之间()
应该是一个有效的扩展方法,但是当我尝试它不工作。事实上,没有从该页面的工作方法时,我尝试一下。
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.
我是什么做错了吗?
扩展方法不能适用于动态
的对象,好像他们是成员的方法。
Extension methods can not be applied to dynamic
objects as if they were member methods.
计数()
是 System.Linq.Queryable
定义的扩展方法,你可以直接调用它您的动态对象:
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)
上一篇:Visual Studio的外壳 - 创建自定义的IDE自定义、外壳、Visual、Studio
下一篇:的System.Uri实现ISerializable的,但给错误?错误、System、Uri、ISerializable