Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting a list into multiple lists in C#

Tags:

list

c#-4.0

I have a list of strings which I send to a queue. I need to split up the list so that I end up with a list of lists where each list contains a maximum (user defined) number of strings. So for example, if I have a list with the following A,B,C,D,E,F,G,H,I and the max size of a list is 4, I want to end up with a list of lists where the first list item contains: A,B,C,D, the second list has: E,F,G,H and the last list item just contains: I. I have looked at the “TakeWhile” function but am not sure if this is the best approach. Any solution for this?

like image 545
Retrocoder Avatar asked Nov 05 '10 09:11

Retrocoder


1 Answers

You can set up a List<IEnumerable<string>> and then use Skip and Take to split the list:

IEnumerable<string> allStrings = new[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" };

List<IEnumerable<string>> listOfLists = new List<IEnumerable<string>>();
for (int i = 0; i < allStrings.Count(); i += 4)
{                
    listOfLists.Add(allStrings.Skip(i).Take(4)); 
}

Now listOfLists will contain, well, a list of lists.

like image 189
Fredrik Mörk Avatar answered Oct 31 '22 14:10

Fredrik Mörk