按价值分组

时间:2013-10-17 19:25:53

标签: c# linq

我有这两个类:

class ZoneInformation : Scores
{
    public string Zone {get;set;}
}

class Scores
{
    public string TypeQ {get;set;}
    public int High {get;set;}
    public int Low {get;set;}
}

我创建了一个这样的集合:区域和每个区域有3种不同的类型:

Collection<ZoneInformation> Values = new Collection<ZoneInformation>();

Values.Add(new ZoneInformation{TypeQ="Type1", Zone="Zone1", High=5, Low=6});
Values.Add(new ZoneInformation{TypeQ="Type2", Zone="Zone1", High=7, Low=8});
Values.Add(new ZoneInformation{TypeQ="Type3", Zone="Zone1", High=9, Low=10});

Values.Add(new ZoneInformation{TypeQ="Type1", Zone="Zone2", High=11, Low=12});
Values.Add(new ZoneInformation{TypeQ="Type2", Zone="Zone2", High=13, Low=14});
Values.Add(new ZoneInformation{TypeQ="Type3", Zone="Zone2", High=15, Low=16});

如何将所有区域的“值”集合的元素“分组”?像这样

new Scores{TypeQ="Type1", High=16, Low=18});

正如你可以看到High = 5 + 11,两个'Type1'的总和

2 个答案:

答案 0 :(得分:4)

对于Linq来说,这非常简单:

var groups = Values.GroupBy(zi => zi.TypeQ)
                   .Select(g => new Scores
                         {
                         TypeQ = g.Key, 
                         High  = g.Sum(zi=> zi.High), 
                         Low   = g.Sum(zi=> zi.Low)
                         }
              );

答案 1 :(得分:1)

其他人说的话或其他语法:

var res = from q in Values
          group q by q.TypeQ into x
          select new Scores()
          {
              TypeQ = x.Key,
              High = x.Sum( y => y.High ),
              Low = x.Sum( y => y.Low ),
          };