将字典拆分为多个大小相等的字典

Split dictionary into multiple equal sized dictionaries

我有一个 Dictionary 如下所示。假设 Dictionary 中有 400 个元素,我想将此 Dictionary 拆分为 4 个大小相等的字典。我该怎么做呢?对于列表,我可以使用一个范围方法,但不确定在这里做什么?

我不关心 Dictionary 是如何分割的,只是为了让它们大小相等。

Dictionary<string, CompanyDetails> coDic;

您可以使用简单的模数对字典进行分组:

int numberOfGroups = 4;
int counter = 0;

var result = dict.GroupBy(x => counter++ % numberOfGroups);

模数 (%) 使 GroupBy 被限制在 0..3 范围内的数字(实际上是 0..numberOfGroups - 1)。这将为您进行分组。

这个问题有一个问题是它不保留顺序。这个是:

decimal numberOfGroups = 4;
int counter = 0;
int groupSize = Convert.ToInt32(Math.Ceiling(dict.Count / numberOfGroups));

var result = dict.GroupBy(x => counter++ / groupSize);

我将使用以下查询:

Dictionary<string, CompanyDetails>[] result =
    dict
        .Select((kvp, n) => new { kvp, k = n % 4 })
        .GroupBy(x => x.k, x => x.kvp)
        .Select(x => x.ToDictionary(y => y.Key, y => y.Value))
        .ToArray();

这里的优点是避免关闭计数器,因为 .Select((kvp, n) => ...) 语句有一个内置的计数器。

我在这段代码中合并了帖子。例如,结果是 IEnumerable<Dictionary<string, string>> 用于 foreach

int counter = 0;
int groupSize = 5;
IEnumerable<Dictionary<string, string>> result = info
    .GroupBy(x => counter++ / groupSize)
    .Select(g => g.ToDictionary(h => h.Key, h => h.Value));

foreach (Dictionary<string, string> rsl in result) {
    // your code
}