将列表拆分为C#中的多个列表

Ret*_*der 9 list c#-4.0

我有一个字符串列表,我发送到队列.我需要拆分列表,以便最终得到一个列表列表,其中每个列表包含最大(用户定义)字符串数.因此,例如,如果我有一个列表,其中包含以下A,B,C,D,E,F,G,H,I和列表的最大大小为4,我想最终得到一个列表列表第一个列表项包含:A,B,C,D,第二个列表有:E,F,G,H,最后一个列表项只包含:I.我查看了"TakeWhile"函数,但不确定是否这是最好的方法.对此有何解决方案?

Fre*_*örk 19

您可以设置a List<IEnumerable<string>>然后使用Skip和Take拆分列表:

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)); 
}
Run Code Online (Sandbox Code Playgroud)

现在listOfLists将包含列表清单.


RPM*_*984 17

/// <summary>
/// Splits a <see cref="List{T}"/> into multiple chunks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list to be chunked.</param>
/// <param name="chunkSize">The size of each chunk.</param>
/// <returns>A list of chunks.</returns>
public static List<List<T>> SplitIntoChunks<T>(List<T> list, int chunkSize)
{
    if (chunkSize <= 0)
    {
        throw new ArgumentException("chunkSize must be greater than 0.");
    }

    List<List<T>> retVal = new List<List<T>>();
    int index = 0;
    while (index < list.Count)
    {
        int count = list.Count - index > chunkSize ? chunkSize : list.Count - index;
        retVal.Add(list.GetRange(index, count));

        index += chunkSize;
    }

    return retVal;
}
Run Code Online (Sandbox Code Playgroud)

参考:http://www.chinhdo.com/20080515/chunking/