我有一个用 C# 编写的应用程序。在这个应用程序中,我有一些代码在两个数据源之间加入一些数据。该代码如下所示:
Result result = new Result();
var items = from userOrder in UserOrders
join product in UserProducts on userOrder.OrderId equals prodcut.OrderId
orderby userOrder.Date, product.Name
select new
{
OrderDate = userOrder.Date,
ProductName = product.Name,
};
result.Items = items.ToList();
代码的最后一行创建了一个编译时错误:
Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: DateTime OrderDate, string ProductName>>' to 'System.Collections.Generic.List<dynamic>'
随着此错误的传达,Items
我的属性(property)Result
对象当前是 List<dynamic>
.我可以更改此属性的类型。但是,我需要这个属性,以便我可以遍历 Items
在我的报告中。我的问题是,什么类型的属性(property)应该 Items
是吗?
最佳答案
您正在使用此行将此列表转换到匿名对象:
select new
{
OrderDate = userOrder.Date,
ProductName = product.Name,
};
尝试在 New 之后添加 result.Items 的类型:
select new TYPE
{
OrderDate = userOrder.Date,
ProductName = product.Name,
};
编辑:Items 的类型好像是动态列表?您应该为这些创建硬类型。您正在混合使用动态对象和匿名对象。
你可以这样做:
result.Items = ((IEnumerable<dynamic>)items).ToList();
但我通常建议仅使用硬类型,因为您可以获得编译类型检查并且不会遇到像您在这里遇到的错误。
编辑 #2:这是我所说的“硬类型”的示例
public class UserOrderProduct
{
public DateTime OrderDate { get; set; }
public string ProductName { get; set; }
}
现在最终的选择是:
select new UserOrderProduct
{
OrderDate = userOrder.Date,
ProductName = product.Name,
};
并且不要忘记将 result.Items 的类型更改为:
List<UserOrderProduct>
关于c# - LINQ - 创建一个属性来存储 LINQ 语句的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40381038/