C#Linq,对象定义不包含属性 [英] C# Linq, object definition does not contains a property
本文介绍了C#Linq,对象定义不包含属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要您的帮助
我刚刚编写了以下代码
var anynomousObject = new { Amount = 10, weight = 20 };
List<object> ListOfAnynomous = new List<object> { anynomousObject };
var productQuery =
from prod in ListOfAnynomous
select new { prod.Amount, prod.weight }; // here it object on 'prod.Amount, prod.weight' that the object defenetion does not contains the "Amount" and "weight" properties
foreach (var v in productQuery)
{
Console.WriteLine(v.Amount, v.weight);
}
所以请您帮我解决这个问题.
so please could you help me to solve this problem.
推荐答案
您需要创建对象定义的类,或者使用动态键盘而不是在对象中装箱:
You need to make a class of your object definition, or using the dynamic keywork instead of boxing in object :
var anynomousObject = new { Amount = 10, weight = 20 };
List<dynamic> ListOfAnynomous = new List<dynamic> { anynomousObject };
var productQuery =
from prod in ListOfAnynomous
select new { prod.Amount, prod.weight };
foreach (var v in productQuery)
{
Console.WriteLine(v.Amount, v.weight);
}
这是因为,当您将其装箱为对象时,编译器不知道匿名var的定义. Dynamic使它在运行时而不是在编译时求值.
this is because, when you box as object, the compiler doesn't know the definition of your anonymous var. Dynamic make it evaluate at runtime instead of compile-time.
另一种选择是创建一个类或结构.
The other option is to create a class or struct.
这篇关于C#Linq,对象定义不包含属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文