Doug
Doug

Reputation: 6518

aggregate list with linq with sum

i am trying to consolidate an ienumerable list that i am serializing

i have data that looks like this:

Internet explorer    10
Internet explorer    15 
Mozille firefox      10

I was it to look like:

Internet explorer    25
Mozille firefox      10

my class looks like:

 public class BrowserVisits
 {
  public string BrowserName { get; set; }

  public int Visits { get; set; }
        }

my current query to serialize an ienumerable list (r) looks like:

var browserVisits = from r in reportData
      select new BrowserVisits
      {
       BrowserName = r.Dimensions.First(d => d.Key == Dimension.Browser).Value,
       Visits = int.Parse(r.Metrics.First(d => d.Key == Metric.Visits).Value)
      };

how do i go a group by with sum in linq?

do i need to go two queries, or can i do a single one.

apologies if this sounds vague, its been a long day, but am more than happy to add to this if it needs clarification

Upvotes: 2

Views: 2628

Answers (3)

Nikunj
Nikunj

Reputation: 307

Name                     Value

Internet explorer      10
Internet explorer      15
Mozille firefox           10

var sum= list.GroupBy(a => a.Name).Select(a => new { Total= a.Sum(b => b.value),Name= a.Key }).OrderByDescending(a => a.Total).ToList();

Upvotes: 0

user372724
user372724

Reputation:

var lstBrowserVisits = new List<BrowserVisits> 
            { 

                new BrowserVisits{BrowserName = "Internet explorer", Visits = 10},
                new BrowserVisits{BrowserName = "Internet explorer", Visits = 15},
                new BrowserVisits{BrowserName = "Mozille firefox", Visits = 10} 
            }; 

var res = (from browserVisit in lstBrowserVisits
           group browserVisit by browserVisit.BrowserName into g
           select new { BrowserName = g.Key, Visits = g.Sum(s => s.Visits) });

Upvotes: 3

cdhowie
cdhowie

Reputation: 168978

What about:

public static IEnumerable<BrowserVisits> SumGroups(
    IEnumerable<BrowserVisits> visits)
{
    return visits.GroupBy(
        i => i.BrowserName,
        (name, browsers) => new BrowserVisits() {
            BrowserName = name,
            Visits = browsers.Sum(i => i.Visits)
        });
}

This works for me against your sample data.

Upvotes: 3

Related Questions