汇总表与LINQ总和 [英] aggregate list with linq with sum

查看:195
本文介绍了汇总表与LINQ总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图巩固我正在序列化

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

我有一个看起来像这样的数据一个IEnumerable列表:

i have data that looks like this:

Internet explorer    10
Internet explorer    15 
Mozille firefox      10

我是它看起来像:

Internet explorer    25
Mozille firefox      10

我的课是这样的:

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

  public int Visits { get; set; }
        }



我目前的查询序列化一个IEnumerable列表(R)是这样的:

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



我该如何去一组由总和LINQ?

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

推荐答案

什么:

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.

这篇关于汇总表与LINQ总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆