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

mHe*_*pMe 7 .net c# dictionary split

我有Dictionary如下所示.假设Dictionary我想要将400个元素拆分Dictionary成4个大小相等的字典.我该怎么做呢?有了列表,我可以使用范围方法,但不知道该怎么做?

我不在乎它Dictionary是如何分裂的,以便它们具有相同的大小.

Dictionary<string, CompanyDetails> coDic;
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 11

您可以使用简单模数将字典分组:

int numberOfGroups = 4;
int counter = 0;

var result = dict.GroupBy(x => counter++ % numberOfGroups);
Run Code Online (Sandbox Code Playgroud)

模数(%)使得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);
Run Code Online (Sandbox Code Playgroud)

  • 可能有类似的东西:`.Select(g => g.ToDictionary(h => h.Key,h => h.Value))`````````````````````````````````` (2认同)