GrahamJRoy
GrahamJRoy

Reputation: 1643

Mapping Linq Group By Results To An Object

I have a class that acts as a summary which is going to be passed to an MVC View as an IEnumerable. The class looks like:

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

The results returned from the db have all of the single entries and so I use linq to summarise these using:

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

When I try and cast the results into my object however I just keep getting an error that:

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

Is there a way to cast the results of the linq query into an enumerable of my class?

Upvotes: 2

Views: 3560

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460028

You cannot cast the anonymous type to FixedLineSummary since both are not related at all(for the compiler). Instead you need to create instances of your class manually:

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

Upvotes: 5

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

You should change the projection to create your class, rather than an anonymous type:

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

Upvotes: 6

Related Questions