2

MVC ビューに IEnumerable として渡されるサマリーとして機能するクラスがあります。クラスは次のようになります。

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

データベースから返された結果には単一のエントリがすべて含まれているため、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 クエリの結果をクラスの列挙型にキャストする方法はありますか?

4

2 に答える 2

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)
              };
于 2012-11-16T14:46:22.367 に答える
5

FixedLineSummary両方が(コンパイラにとって)まったく関連していないため、匿名型をにキャストすることはできません。代わりに、クラスのインスタンスを手動で作成する必要があります。

IEnumerable<FixedLineSummary> summaries = summary
   .Select(s => new FixedLineSummary
   {
        CustomerId = s.CustomerId,
        CustomerName = s.CustomerName,
        NumberOfLines = s.NumberOfLines,
        SiteName = s.SiteName
   })
   .ToList();
于 2012-11-16T14:47:56.483 に答える