aggregate list with linq with sum

最后都变了- 提交于 2019-12-11 02:41:26

问题


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


回答1:


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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/4487357/aggregate-list-with-linq-with-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!