c# - LINQ - 创建一个属性来存储 LINQ 语句的结果

标签 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我的属性(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/

相关文章:

c# - 将 BsonDocument 映射到类但出现错误

c# - .NET Architectural issue : 2 Web Services, 如何更改在运行时使用哪一个?

c# - 从 .NET 4 WinForm 应用程序控制 Delphi 7 表单

c# - linq2sql图片保存问题

c# - 当与 orderby 一起使用时,是否存在 ascending 关键字纯粹是为了清楚起见?

c# - 如何在 MVC Controller 中使用 Linq 连接两个表

C# Lock 语法 - 2 个问题

c# - 如何在 asp.net c# 上制作一个真正的 XLS 文件?

c# - LINQ 如果 .Any 匹配 .Any

.net - 使用与声明上下文变量相比有优势吗?