linq lambda Group Byの使い方

4607 ワード

Linqでは複数の値でグループ化(Group By)
 
/// <summary> </summary>

class Employee {

   public int ID { get;set; }

   public string FName { get; set; }

   public int Age { get; set; }

   public char Sex { get; set; }

}

このクラスのAgeとSexの連続するフィールドをグループ化すると、次のようになります.
//  

List<Employee> empList = new List<Employee>();

empList.Add(new Employee() {

   ID = 1, FName = "John", Age = 23, Sex = 'M'

});

empList.Add(new Employee() {

   ID = 2, FName = "Mary", Age = 25, Sex = 'F'

});



empList.Add(new Employee() {

   ID = 3, FName = "Amber", Age = 23, Sex = 'M'

});

empList.Add(new Employee() {

   ID = 4, FName = "Kathy", Age = 25, Sex = 'M'

});

empList.Add(new Employee() {

   ID = 5, FName = "Lena", Age = 27, Sex = 'F'

});



empList.Add(new Employee() {

   ID = 6, FName = "Bill", Age = 28, Sex = 'M'

});



empList.Add(new Employee() {

   ID = 7, FName = "Celina", Age = 27, Sex = 'F'

});

empList.Add(new Employee() {

   ID = 8, FName = "John", Age = 28, Sex = 'M'

});

次の方法は、
//  key 

var sums = empList

         .GroupBy(x => new { x.Age, x.Sex })

         .Select(group => new {

            Peo = group.Key, Count = group.Count()

         });

foreach (var employee in sums) {

   Console.WriteLine(employee.Count + ": " + employee.Peo);

}



//  key lambda 

var sums2 = from emp in empList

            group emp by new { emp.Age, emp.Sex } into g

            select new { Peo = g.Key, Count = g.Count() };

foreach (var employee in sums) {

   Console.WriteLine(employee.Count + ": " + employee.Peo);

}

この例では匿名タイプを十分に利用している.
 
varListByOwner= list.GroupBy(l => l.Owner)                          .Select(lg =>                                 new{                                     Owner= lg.Key,                                     Boxes= lg.Count(),                                    TotalWeight= lg.Sum(w => w.Weight),                                     TotalVolume= lg.Sum(w => w.Volume)                                 });
 var q =from b in listOfBoxes                group b by b.Ownerinto g                selectnew                           {                               Owner= g.Key,                               Boxes= g.Count(),                               TotalWeight= g.Sum(item => item.Weight),                               TotalVolume= g.Sum(item => item.Volume)                           };