带有linq和sum的聚合列表

时间:2010-12-20 06:19:26

标签: c# linq linq-to-objects

我正在尝试合并一个我正在序列化的可列表

我的数据如下:

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

我当前查询序列化一个可列表的列表(r)如下:

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中使用sum来分组?

我需要进行两次查询,还是可以进行一次查询。

如果这听起来含糊不清,那么这是一个漫长的一天,但如果需要澄清,我很乐意加入其中

3 个答案:

答案 0 :(得分:3)

怎么样:

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

这对我的样本数据起作用。

答案 1 :(得分:3)

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

答案 2 :(得分:0)

名称值

Internet Explorer 10 Internet explorer 15
Mozilla 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();