2013-10-17 76 views
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}); 

正如你所看到的高= 5 + 11,兩者之和 '的Type1'

回答

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) 
         } 
      ); 
+0

+1你更快,也正確。 – Habib

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), 
      };