将Linq Group按结果映射到对象

时间:2012-11-16 14:42:53

标签: c# linq ienumerable

我有一个作为摘要的类,它将作为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查询的结果转换为我的类的可枚举?

2 个答案:

答案 0 :(得分:6)

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

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)
              };

答案 1 :(得分:5)

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

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