如何使用LINQ将多个列组合在一个层次结构中

时间:2016-03-28 04:07:20

标签: c# entity-framework linq

这是一个演示模型:

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

这是我到目前为止的代码:

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

这给了我这样的东西:

[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 },
    }
}

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

我们必须在层次结构中应用GroupBy两次,首先是Year ant,然后是Month

这应该适合你。

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

检查工作Example