IGrouping <int,keypair =“”>到词典

时间:2015-10-13 20:58:24

标签: c# dictionary

我把我的主要dictonary分成了一组多个dictonaries,以便我可以用较小的一组dictonaries拍摄线程。

以下是将我的主要Dictonary分成多个较小的代码的代码:

int numberOfGroups = 10;
int counter = 0;
var result = offenderWorkload.GroupBy(x => counter++ % numberOfGroups);

现在我无法在结果中从10组中获得一个dictonary。

我需要将结果分成10个不同的dictonaries并拍摄线程,就像......

foreach(var something in result)
{
    Dictionary<String, int> workLoad = (Dictionary<String, int>)something.ToDictionary();
    Console.WriteLine("workload: " + something.Key + " has " + workLoad.Keys.Count);
}

因此,某些东西是关键对,它被转移到dictonary并忽略了Igroup中的int。

2 个答案:

答案 0 :(得分:2)

Dictionary<String, int> workLoad = something.ToDictionary(x => x.Key, x => x.Value);

因为在分组后,每个分组成员不是字典,而是KeyValuePair的集合。

答案 1 :(得分:0)

这将为您提供一组词典。每个字典都有n个元素。

int n = (int)Math.Ceiling((double)offenderWorkload.Count/numberOfGroups);

IEnumerable<Dictionary<string, int>> result =
    offenderWorkload.GroupBy(x => counter++/n)
        .Select(x => x.ToDictionary(d => d.Key, d => d.Value));

请注意,如果您的词典有12个键,并且您想将它们分组到5个词典中,那么您将获得4个词典,每个词都有3个词典。

因为12/5 = 2.4。你可以拥有5个带有2个键的词典和一个带有两个键2*5+0.4*5的词典。共有6个字典,超过最大组数。 更好的方法,通过取其上限,您将获得最大可能(或更少)指定组的数量。这里[2.4] = 3。总共4个词典每个都有3个键。

另一个例子,如果你想将12组分为7个词典,你将获得5个词典,而每个词典都有2个键。如果将13组分为3组,您将获得3个词典,两个首字典将有5个键,最后一个有3个键。

为了获得您指定的最大numberOfGroups,请选择offenderWorkload.Count可以分割的内容。例如,如果将12分组为6,您将获得6个词典,每个词典有2个键(12 / 6 = 2)。

int numberOfGroups = 10;
int counter = 0;
int n = (int)Math.Ceiling((double)offenderWorkload.Count/numberOfGroups);

var result =
    offenderWorkload.GroupBy(x => counter++/n)
        .Select(x => x.ToDictionary(d => d.Key, d => d.Value));

int i = 0;
foreach (var workLoad in result)
{
    Console.WriteLine("workload: " + i++ + " has " + workLoad.Keys.Count);
}