LINQ - 创建存储LINQ语句结果的属性

时间:2016-11-02 13:21:39

标签: c# linq

我有一个用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对象上的Result属性目前为List<dynamic>。我可以改变这个属性的类型。但是,我需要这个属性,以便我可以遍历报告中的Items。我的问题是,Items应属于哪种类型的财产?

2 个答案:

答案 0 :(得分:2)

您将此列表转换为具有以下行的匿名对象:

select new
            {
              OrderDate = userOrder.Date,
              ProductName = product.Name,
            };

尝试在New:

之后添加result.Items的类型
  select new TYPE
                {
                  OrderDate = userOrder.Date,
                  ProductName = product.Name,
                };

编辑:看起来物品的类型可能是动态列表?您应该为这些创建一个硬类型。 混合动态和匿名对象。

你可以这样做:

result.Items = ((IEnumberable<dynamic>)items).ToList();

但我通常建议只使用硬类型,因为你获得了编译类型检查,并且不会遇到像你在这里一样的错误。

Edit2:这是一个我的意思是'硬类型'的例子

 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>

答案 1 :(得分:1)

为什么不起作用

您正在尝试将对象分配给result.Items,它与定义的类型不匹配。 result.Items是动态的,你正在为它分配一个匿名类型。

如何修复

只需创建一个类来保存聚合数据的结果。

public class OrderDetailsSummary
{
    public DateTime OrderDate { get; set; }
    public string ProductName { get; set; }
}

更改您的Linq查询以使用此功能。

select new OrderDetailsSummary
{
    OrderDate = userOrder.Date,
    ProductName = product.Name,
};

将Result类的Items属性更改为OrderDetailsS​​ummary类型。