【问题标题】:Mapping Linq Group By Results To An Object按结果将 Linq 组映射到对象
【发布时间】:2012-11-16 14:42:52
【问题描述】:

我有一个作为摘要的类,它将作为 IEnumerable 传递给 MVC 视图。该类看起来像:

public class FixedLineSummary
{
    public long? CustomerId { get; set; }
    public string CustomerName { get; set; }
    public int? NumberOfLines { get; set; }
    public string SiteName { get; set; }
}

从 db 返回的结果包含所有单个条目,因此我使用 linq 来总结这些:

var summary = (from r in result 
              let k = new {r.CustomerId, CustomerName = r.CompanyName, r.SiteName}
              group r by k into t
              select new 
              {
                  t.Key.CustomerId,
                  t.Key.CustomerName,
                  t.Key.SiteName,
                  Lines = t.Sum(r => r.lines)
              });

当我尝试将结果转换为我的对象时,我只是不断收到一个错误:

Instance argument: cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<Domain.Entities.FixedLineSummary>'

有没有办法将 linq 查询的结果转换为我的类的枚举?

【问题讨论】:

  • 对不起,应该说。只需 .AsEnumerable();

标签: c# linq ienumerable


【解决方案1】:

您应该更改投影以创建您的类,而不是匿名类型:

var summary = from r in result 
              let k = new {r.CustomerId, CustomerName = r.CompanyName, r.SiteName}
              group r by k into t
              select new FixedLineSummary
              {
                  CustomerId = t.Key.CustomerId,
                  CustomerName = t.Key.CustomerName,
                  SiteName = t.Key.SiteName,
                  NumberOfLines = t.Sum(r => r.lines)
              };

【讨论】:

    【解决方案2】:

    您不能将匿名类型转换为FixedLineSummary,因为两者根本不相关(对于编译器)。相反,您需要手动创建类的实例:

    IEnumerable<FixedLineSummary> summaries = summary
       .Select(s => new FixedLineSummary
       {
            CustomerId = s.CustomerId,
            CustomerName = s.CustomerName,
            NumberOfLines = s.NumberOfLines,
            SiteName = s.SiteName
       })
       .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多