2016-03-28 10 views
1

bir hiyerarşi içinde Ben grup birden sütunları Demo Modeli edilir edebilirsiniz: var bugüne kadarnasıl İşte LINQ

public class Foo 
{ 
    public DateTime SomeDate { get; set; } 
    public int SomeValue { get; set; } 
} 

Ve bu kodu: Bu bana böyle bir şey verir

//Some sample data 
var fooList = new List<Foo> { 
    new Foo { SomeDate = DateTime.Now.AddMonths(0), SomeValue = 1 }, 
    new Foo { SomeDate = DateTime.Now.AddMonths(0), SomeValue = 2 }, 
    new Foo { SomeDate = DateTime.Now.AddMonths(6), SomeValue = 3 }, 
    new Foo { SomeDate = DateTime.Now.AddMonths(6), SomeValue = 4 }, 
    new Foo { SomeDate = DateTime.Now.AddMonths(12), SomeValue = 5 }, 
    new Foo { SomeDate = DateTime.Now.AddMonths(12), SomeValue = 6 }, 
    new Foo { SomeDate = DateTime.Now.AddMonths(14), SomeValue = 7 }, 
    new Foo { SomeDate = DateTime.Now.AddMonths(14), SomeValue = 8 } 
}; 

//The query 
var result = from foo in fooList 
      group foo by new { foo.SomeDate.Year, foo.SomeDate.Month } into g 
      select new 
      { 
       //This should be the parent 
       TheYear = g.Key.Year, 

       //This should be the content 
       TheMonth = g.Key.Month, 
       TheSum = g.Sum(e=>e.SomeValue) 
      }; 

: Ben, her yıl kombine oluyor yapmaya çalışıyorum, bu yüzden böyle bir şey ihtiva yıl, bir listesi var ne

[0] = { TheYear = 2016, TheMonth = 3, TheSum = 3 } 
[1] = { TheYear = 2016, TheMonth = 9, TheSum = 7 } 

:

[0] = { 
    TheYear = 2016 
    TheContent = { 
     [0] = { TheMonth = 3, TheSum = 3 }, 
     [1] = { TheMonth = 9, TheSum = 7 }, 
    } 
} 

Bunu nasıl başarabilirim?

cevap

2

GroupBy hiyerarşisinde iki kez karınca ardından Month numaralı telefondan başvurmamız gerekiyor.

Bu sizin için çalışmalıdır.

fooList.GroupBy(g=> new { g.SomeDate.Year }) 
     .Select(s=> 
      new 
      { 
       Year = s.Key, 
       TheContent = s.GroupBy(x=>x.SomeDate.Month) 
          .Select(m=> 
          new 
          { 
           Month = m.Key, 
           TheSum = m.Sum(e=>e.SomeValue) 
          }).ToList() 
      }); 

çalışma Kontrol Example