Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c# - Get sum of the value from list using 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);
            }
        }

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 ....

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not sure if you want to get the sum of every group or the total. If it's the total then this should do the trick

var sum = allData.Sum(x => Int32.Parse(x[2]));

If it's per key then try the following

var all = allData
  .GroupBy(x => x[0])
  .Select(x => x.Sum(y => Int32.Parse(y[2]));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...