Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ merge a collection

Tags:

c#

linq

I need to flatten it to one item in a new collection.

The input will be an IEnumerable collection. The base class looks like this:

    public class ConversionsResult
    {
        public int SiteId { get; set; }

        public int TotalLeads { get; set; }
        public int TotalCalls { get; set; }
        public int TotalEmails { get; set; }
        public int UniqueVisits { get; set; }

        public int MetricYear { get; set; }
        public int MetricMonth { get; set; }
        public string DeviceCategory { get; set; }
    }

The flattened class will look like this:

SiteId, MetricMonth, MetricYear SUM(TotalLeads), SUM(TotalEmails), SUM(UniqueVisits), CONCATENATE(DeviceCategory).

NOTES:

  • SiteId, MetricMonth, MetricYear will have the same value flattened as in the original collection
  • The total properties need to be added
  • DeviceCategory will have three different values in it, comma separated, e.g. "desktop,mobile,tablet".

I could accomplish this another route but I wanted to use LINQ. I tried hacking a few solutions I found but it was a total mess so I've excluded the noise I tried.

like image 524
Will Lopez Avatar asked Dec 12 '25 15:12

Will Lopez


1 Answers

You need to group by (Enumerable.GroupBy) SiteId, MetricMonth and MetricYear and then select results like:

var query  = list.GroupBy(r => new { r.SiteId, r.MetricMonth, r.MetricYear })
            .Select(grp => new
            {
                SiteId = grp.Key.SiteId, 
                MetricMonth = grp.Key.MetricMonth, 
                MetricYear = grp.Key.MetricYear, 
                TotalLeads = grp.Sum(r=> r.TotalLeads), 
                TotalEmails = grp.Sum(r=> r.TotalEmails), 
                UniqueVisits = grp.Sum(r=> r.UniqueVisits), 
                DeviceCategory = String.Join(",", grp.Select(r=> r.DeviceCategory)),
            });
like image 59
Habib Avatar answered Dec 14 '25 03:12

Habib



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!