Split dictionary into several identical dimensional dictionaries

I have a Dictionary shown below. Say a Dictionary has 400 elements. I want to break this Dictionary into 4 dictionaries of equal size. How can I do it? There is a range method on the list that I can use, but not sure what to do here?

I don't care how the Dictionary breaks down so that they are the same size.

 Dictionary<string, CompanyDetails> coDic; 
+6
source share
3 answers

You can use a simple module to group the dictionary in parts:

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

The module ( % ) makes GroupBy restriction a limited number in the range 0..3 (actually 0..numberOfGroups - 1 ). This will make the grouping for you.

The problem though with this is that it does not keep order. It does:

 decimal numberOfGroups = 4; int counter = 0; int groupSize = Convert.ToInt32(Math.Ceiling(dict.Count / numberOfGroups)); var result = dict.GroupBy(x => counter++ / groupSize); 
+9
source

I would use the following query:

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

The advantage here is to avoid closing over the counter, as the .Select((kvp, n) => ...) operator has a built-in counter.

+3
source

I combined the posts in this code. The result is an IEnumerable<Dictionary<string, string>> for use in foreach , for example.

 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 } 
0
source

Source: https://habr.com/ru/post/987038/


All Articles