Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...