Get sum of the value from list using linq?

后端 未结 4 1190
-上瘾入骨i
-上瘾入骨i 2020-12-31 06:57

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

        List> allData = new List<         


        
相关标签:
4条回答
  • 2020-12-31 07:26

    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]));
    
    0 讨论(0)
  • 2020-12-31 07:27

    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]))
                  };
    
    0 讨论(0)
  • 2020-12-31 07:35
    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.

    0 讨论(0)
  • 2020-12-31 07:37

    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());
    
    0 讨论(0)
提交回复
热议问题