문제

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.
도움이 되었습니까?

해결책 2

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

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

다른 팁

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

Sticking as much as possible to the LINQ query language:

var grouped = from d in allData
              group d by i[0] into g
              select new
              {
                  Name = g.Key,
                  Sum = g.Sum(i => int.Parse(i[2]))
              };

This will give you parallel List with each name and the count of how many times each name occurs.

    var names = grouped.Select(s => s.Key).ToList();
    var nameCount = grouped.Select(s => s.Count()).ToList();

Also... you may want to add this when assigning alldata to grouped. I use this to get a List from greatest to least amount of occurrences.

    var grouped = allData.GroupBy(x => x[0]).OrderByDescending(i => i.Count());
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top