Let’s say I have a list of unknown number of elements in string value, I want to divide it to n subarray or lists (n could be any int, for example n=3), what is best way to do it?
note: the number of elements in each group is not necessary to be equal
LINQ GroupBy and Select methods can help:
This code will result in
subListscontaining a list of threeList<string>collections:{"A", "D", "G"},{"B", "E"}and{"C", "F"}. In order to achieve that I based my grouping on element indices in the original list (there is an overload forSelectmethod that lets you do that, see link above). You can use some other logic to select the key.In my example
subListsis aList<List<string>>. If you need an array, useToArraywhere appropriate.EDIT: using modulo operation for grouping may not be a good idea if you care about the way values are distributed between lists. Probably the better option is to do it this way:
This will produce the following result:
{"A", "B", "C"},{"D", "E", "F"},{"G"}which may be more sane way to distribute the values.Bottom line is, you can achieve what you need by using
GroupByandSelectmethods, just provide the correct grouping logic that is suitable for your domain.