Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 200
GrahamJRoy Avatar asked Dec 09 '25 13:12

GrahamJRoy


1 Answers

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)
              };
like image 107
Ahmad Mageed Avatar answered Dec 12 '25 03:12

Ahmad Mageed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!