将列表或集合拆分为块

时间:2015-05-14 21:48:27

标签: c# arrays list split

我有一个程序可以将文件的内容读入某种列表或数组。此列表/数组可以包含任意数量的项目。我需要将它分成更小的组,每组50项,然后对每组中的每个项目进行一些处理。

List<string> stuffFromFile = new List<string>();

while ((line = fileReader.ReadLine()) != null)
      {
           stuffFromFile.Add(line);
      }

我一直在网上浏览一些关于如何分块的例子,但说实话,我并不真正理解这些例子,其中一些似乎过于复杂。我只需要一些简单的东西,将原始的项目列表分块/拆分/分成50个组,然后让我遍历每个组中的每个项目,直到处理完成。

读入的项目总数很可能不是我可以均匀划分50的数字,因此最后一组最有可能包含少于50个项目,但仍然需要像其他项目一样进行处理。 / p>

有人可以帮忙吗?这听起来应该很简单,但我真的不知道该怎么做。我已经看过使用LINQ的例子,但我也不理解。

2 个答案:

答案 0 :(得分:12)

这是一个扩展方法,适用于任何列表和任何大小的块。

public static List<List<T>> SplitList<T>(this List<T> me, int size = 50)
{
    var list = new List<List<T>>();
    for (int i = 0; i < me.Count; i += size)
        list.Add(me.GetRange(i, Math.Min(size, me.Count - i)));
    return list;
} 

像这样使用:

List<List<string>> chunksOf50 = stuffFromFile.SplitList();

答案 1 :(得分:1)

List<string> stuffFromFile = new List<string>() { "1", "2", "3", "4" }; //contents

while (stuffFromFile.Count > 0)
{
    List<string> newChunk = stuffFromFile.Take(50).ToList(); //Take up to 50 elements
    stuffFromFile.RemoveRange(0, newChunk.Count); // Remove the elements you took
}
相关问题