将列表拆分为多个列表
我有一个字符串列表,我发送到队列。我需要拆分列表,以便我最终得到列表的列表,其中每个列表包含最大(用户定义)的字符串数。因此,例如,如果我有一个列表与以下A,B,C,D,E,F,G,H,I和列表的最大大小为4,我想结束一个列表的列表,其中第一个列表项包含:A,B,C,D,第二个列表有:E,F,G,H,最后一个列表项只包含:我已经看了TakeWhile函数,这是最好的方法。
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. Anyone got a solution for this?
您可以设置列表< IEnumerable< string> ;
然后使用跳过
和以
分割列表:
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));
}
现在 listOfLists
包含,以及列表列表。
Now listOfLists
will contain, well, a list of lists.