在C#中将一个列表拆分成多个列表

11

我有一个字符串列表,我将其发送到队列中。 我需要拆分列表,以便最终得到一个包含最大(用户定义的)数量的字符串的列表列表。 例如,如果我有以下列表A,B,C,D,E,F,G,H,I,列表的最大大小为4,则我希望最终得到一个列表列表,其中第一个列表项包含:A,B,C,D,第二个列表包含:E,F,G,H,最后一个列表项仅包含:I。 我已经查看了“TakeWhile”函数,但不确定这是否是最佳方法。 有没有解决方案?

3个回答

22
你可以设置一个List<IEnumerable<string>>,然后使用SkipTake来分割列表:
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将包含一个列表,里面又包含了多个列表。


我投票支持这个,因为这正是我所需要的。RPM1984也给了一个不错的答案,但是这个更加适合我的代码。 - Retrocoder
如果我需要将列表分成5个列表,无论这些列表最终包含多少个字符串,该怎么办? - Skuta

21
/// <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;
}

参考资料:http://www.chinhdo.com/20080515/chunking/ 本文将讨论分块技术及其如何在IT领域中应用。分块是一种将大型数据集分成小块以便更好地处理的方法。在IT领域,分块可用于优化数据库查询、网络传输和文件读取等操作。使用分块技术可以提高系统效率并减少资源占用。

你的方法真是太棒了!它完全做到了我想要的。 - Benjamin

4

一些相关阅读:

否则,对于可枚举对象(用于惰性加载和处理,以防列表很大/昂贵),可以对已接受的答案进行微小变化。我要指出,实例化每个块/段(例如通过.ToList.ToArray,或者只是枚举每个块)可能会产生副作用--请参见测试。

方法

// so you're not repeatedly counting an enumerable
IEnumerable<IEnumerable<T>> Chunk<T>(IEnumerable<T> list, int totalSize, int chunkSize) {
    int i = 0;
    while(i < totalSize) {
        yield return list.Skip(i).Take(chunkSize);
        i += chunkSize;
    }
}
// convenience for "countable" lists
IEnumerable<IEnumerable<T>> Chunk<T>(ICollection<T> list, int chunkSize) {
    return Chunk(list, list.Count, chunkSize);
}
IEnumerable<IEnumerable<T>> Chunk<T>(IEnumerable<T> list, int chunkSize) {
    return Chunk(list, list.Count(), chunkSize);
}

测试(Linqpad)

(注意:我必须包括 Assert 方法以供 Linqpad 使用)

void Main()
{
    var length = 10;
    var size = 4;

    test(10, 4);
    test(10, 6);
    test(10, 2);
    test(10, 1);

    var sideeffects = Enumerable.Range(1, 10).Select(i => {
        string.Format("Side effect on {0}", i).Dump();
        return i;
    });

    "--------------".Dump("Before Chunking");
    var result = Chunk(sideeffects, 4);
    "--------------".Dump("After Chunking");
    result.Dump("SideEffects");
    var list = new List<int>();
    foreach(var segment in result) {
        list.AddRange(segment);
    }
    list.Dump("After crawling");

    var segment3 = result.Last().ToList();
    segment3.Dump("Last Segment");
}

// test
void test(int length, int size) {
    var list = Enumerable.Range(1, length);

    var c1 = Chunk(list, size);

    c1.Dump(string.Format("Results for [{0} into {1}]", length, size));

    Assert.AreEqual( (int) Math.Ceiling( (double)length / (double)size), c1.Count(), "Unexpected number of chunks");
    Assert.IsTrue(c1.All(c => c.Count() <= size), "Unexpected size of chunks");
}

我找到的最佳解决方案是来自MoreLinq -- https://code.google.com/p/morelinq/source/browse/MoreLinq/Batch.cs - drzaus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接