使用linq从列表中获取值的总和? [英] Get sum of the value from list using linq?

查看:69
本文介绍了使用linq从列表中获取值的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用linq从列表列表中获取值的总和?我的数据如下代码

I am trying to get the sum of the value from list of list using linq ?my data is as below code

        List<List<string>> allData = new List<List<string>>();
        using (StreamReader reader = new StreamReader(path))
        {
            while (!reader.EndOfStream)
            {
                List<string> dataList;
                dataList = reader.ReadLine().Split('|').ToList();
                allData.Add(dataList);
            }
        }

allData中为我提供了如下数据

which gives me data in allData as below

           allData-->[0]-->[0]-'name1'
                           [1]-'sub'
                           [2]-'12'
                     [1]-->[0]-'name2'
                           [1]-'sub'
                           [2]-'15'  
                     [2]-->[0]-'name1'
                           [1]-'sub2'
                           [2]-'15'
    //and so on ....

我已经应用了group by,从而可以按名称对我进行分组,但是我无法弄清楚如何获得每个名称的分数总和?

i have applied group by that gives me grouping by the name but i am not able to figure out how to get the sum of the marks for each name ?

      var grouped = allData.GroupBy(x => x[0]);

在此之后,我将所有匹配的名称分组为一个,但是现在如何获取该组的标记总和?任何帮助都会很棒吗?

after this i get all matching name grouped into one but now how to get sum of the marks for that group ? any help would be great ?

  Output should be  name1=27 and name2=15 and so on.

推荐答案

var grouped = allData.GroupBy(x => x[0])
                     .Select(g => new
                     {
                         Name = g.Key,
                         Sum = g.Sum(x => int.Parse(x[2]))
                     });

它将为每个组返回一个匿名类型实例,该实例具有两个属性:带有分组键的Name和带有标记和的Sum.

It will return an anonymous type instance for each group, with two properties: Name with your grouping key and Sum with sum of marks.

这篇关于使用linq从列表中获取值的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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