Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将Linq Group By结果映射到对象_C#_Linq_Ienumerable - Fatal编程技术网

C# 将Linq Group By结果映射到对象

C# 将Linq Group By结果映射到对象,c#,linq,ienumerable,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; } } d

我有一个类作为摘要,它将作为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>'
实例参数:无法从'System.Linq.IQueryable'转换为'System.Collections.Generic.IEnumerable'

有没有办法将linq查询的结果强制转换为my类的可枚举项?

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

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

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

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

对不起,我应该说。仅使用.AsEnumerable();