将列表拆分为多个列表 [英] spliting a list into multiple lists

查看:134
本文介绍了将列表拆分为多个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串列表,我发送到队列。我需要拆分列表,以便我最终得到列表的列表,其中每个列表包含最大(用户定义)的字符串数。因此,例如,如果我有一个列表与以下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.

这篇关于将列表拆分为多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆