在C#中将列表拆分为多个列表 [英] splitting a list into multiple lists in C#
问题描述
我有一个发送到队列的字符串列表.我需要拆分列表,以便最终得到一个列表列表,其中每个列表都包含最大(用户定义)的字符串数.因此,例如,如果我有一个包含以下A,B,C,D,E,F,G,H,I的列表,并且列表的最大大小为4,则我想以列表列表结尾,其中第一个列表项包含:A,B,C,D,第二个列表项包含:E,F,G,H,最后一个列表项仅包含:I.我看过"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. Any solution for this?
推荐答案
您可以设置List<IEnumerable<string>>
,然后使用Skip
和Take
拆分列表:
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.
这篇关于在C#中将列表拆分为多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!