如何压缩字典字典并使用LINQ对内部字典的值进行求和?

时间:2012-04-16 11:27:55

标签: vb.net linq

我有以下对象:

countDictionary As Dictionary(of Category, Dictionary(of Date, Integer))

Class有一个枚举属性。出于演示的目的,我将其称为MasterCategory

我一直试图找出一个如下所示的对象:

groupedCountDictionary As Dictionary(of MasterCategory, Dictionary(of Date, Integer)

我能得到的最好结果是:

Lookup(of MasterCategory, Dictionary(of Date, Integer))

自:

countDictionary.ToLookup(Function(o) o.Key.MasterCategory, Function(o) o.Value)

每个IEnumerable (Of Dictionary(of Date, Integer))值会产生MasterCategory

但是,我需要将IEnumerable of Dictionary 扁平化为一个字典,每个日期的所有整数相加(总计数)。

然后我尝试使用各种selectgroup by s(来自众多stackoverflow帖子)来“压扁”它,但我的努力不足。

有人可以建议一种方法吗?如果可能,寻找 VB.Net 答案。

修改

当前代码

[Category Class]
-    MasterCategory As Enum
-    Name As String etc

[countDictionary As Dictionary(of Category Objects, Dictionary(of Date, Integer))]
-    length 8
-    Children of 8 Categories:
        3 with MasterCategory A, 1097 int's by date
        4 with MasterCategory B, 1097 int's by date
        1 with MasterCategory C, 1097 int's by date

尽力而为

[Lookup(of MasterCategory, Dictionary(of Date, Integer)]
-    length 3
-    Children of 3 Master Categories:
     1 of IEnumerable(of Dictionary(of Date, Integer)) and length 3
         3 x Dictionary length 1097 int's by date

     1 of IEnumerable(of Dictionary(of Date, Integer)) and length 4
         3 x Dictionary length 1097 int's by date

     1 of IEnumerable(of Dictionary(of Date, Integer)) and length 1
         3 x Dictionary length 1097 int's by date

必需

[Dictionary(MasterCategory, Dictionary(of Date, Integer))]
-    length 3
-    Children of 3 Master Categories:
     3 of Dictionary(of Date, Integer) with summed total int's

1 个答案:

答案 0 :(得分:1)

你是否在SelectMany之后?如果是这样,这可能会做你想要的事情:

C#

test.SelectMany(x => x.Key.MasterCategory).Sum(x => x.ThePropertyToSum)

在VB中,我认为是:

test.SelectMany(Function(x) x.Key.MasterCategory).Sum(Function(x) x.ThePropertyToSum)