3

我有这两个类:

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' 的总和

4

2 回答 2

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)
                         }
              );
于 2013-10-17T19:28:57.943 回答
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 ),
          };
于 2013-10-17T19:36:33.333 回答