293

我正在尝试将列表拆分为一系列较小的列表。

我的问题:我的拆分列表的功能没有将它们拆分为正确大小的列表。它应该将它们拆分为大小为 30 的列表,而是将它们拆分为大小为 114 的列表?

如何使我的函数将列表拆分为 X 个大小为30 或更少的列表?

public static List<List<float[]>> splitList(List <float[]> locations, int nSize=30) 
{       
    List<List<float[]>> list = new List<List<float[]>>();

    for (int i=(int)(Math.Ceiling((decimal)(locations.Count/nSize))); i>=0; i--) {
        List <float[]> subLocat = new List <float[]>(locations); 

        if (subLocat.Count >= ((i*nSize)+nSize))
            subLocat.RemoveRange(i*nSize, nSize);
        else subLocat.RemoveRange(i*nSize, subLocat.Count-(i*nSize));

        Debug.Log ("Index: "+i.ToString()+", Size: "+subLocat.Count.ToString());
        list.Add (subLocat);
    }

    return list;
}

如果我在大小为 144 的列表上使用该函数,则输出为:

索引:4,大小:120
索引:3,大小:114
索引:2,大小:114
索引:1,大小:114
索引:0,大小:114

4

21 回答 21

482

我建议使用此扩展方法将源列表按指定的块大小分块到子列表:

/// <summary>
/// Helper methods for the lists.
/// </summary>
public static class ListExtensions
{
    public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize) 
    {
        return source
            .Select((x, i) => new { Index = i, Value = x })
            .GroupBy(x => x.Index / chunkSize)
            .Select(x => x.Select(v => v.Value).ToList())
            .ToList();
    }
}

例如,如果您将 18 个项目的列表按每个块 5 个项目分块,它会为您提供 4 个子列表的列表,其中包含以下项目:5-5-5-3。

注意:在即将到来的分块改进中LINQ.NET 6将像这样开箱即用:

const int PAGE_SIZE = 5;

IEnumerable<Movie[]> chunks = movies.Chunk(PAGE_SIZE);
于 2014-06-06T17:02:53.180 回答
369
public static List<List<float[]>> SplitList(List<float[]> locations, int nSize=30)  
{        
    var list = new List<List<float[]>>(); 

    for (int i = 0; i < locations.Count; i += nSize) 
    { 
        list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i))); 
    } 

    return list; 
} 

通用版本:

public static IEnumerable<List<T>> SplitList<T>(List<T> locations, int nSize=30)  
{        
    for (int i = 0; i < locations.Count; i += nSize) 
    { 
        yield return locations.GetRange(i, Math.Min(nSize, locations.Count - i)); 
    }  
} 
于 2012-07-13T03:37:40.567 回答
50

怎么样:

while(locations.Any())
{    
    list.Add(locations.Take(nSize).ToList());
    locations= locations.Skip(nSize).ToList();
}
于 2012-07-13T03:38:53.663 回答
45

MoreLinq有方法调用Batch

List<int> ids = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // 10 elements
int counter = 1;
foreach(var batch in ids.Batch(2))
{
    foreach(var eachId in batch)
    {
        Console.WriteLine("Batch: {0}, Id: {1}", counter, eachId);
    }
    counter++;
}

结果是

Batch: 1, Id: 1
Batch: 1, Id: 2
Batch: 2, Id: 3
Batch: 2, Id: 4
Batch: 3, Id: 5
Batch: 3, Id: 6
Batch: 4, Id: 7
Batch: 4, Id: 8
Batch: 5, Id: 9
Batch: 5, Id: 0

ids被分成 5 个带有 2 个元素的块。

于 2017-09-25T13:04:26.603 回答
15

Serj-Tm 解决方案很好,这也是作为列表扩展方法的通用版本(将其放入静态类):

public static List<List<T>> Split<T>(this List<T> items, int sliceSize = 30)
{
    List<List<T>> list = new List<List<T>>();
    for (int i = 0; i < items.Count; i += sliceSize)
        list.Add(items.GetRange(i, Math.Min(sliceSize, items.Count - i)));
    return list;
} 
于 2014-10-01T12:39:36.603 回答
13

.NET 6 更新

var originalList = new List<int>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}

// split into arrays of no more than three
IEnumerable<int[]> chunks = originalList.originalList.Chunk(3);

在 .NET 6 之前

public static IEnumerable<IEnumerable<T>> SplitIntoSets<T>
    (this IEnumerable<T> source, int itemsPerSet) 
{
    var sourceList = source as List<T> ?? source.ToList();
    for (var index = 0; index < sourceList.Count; index += itemsPerSet)
    {
        yield return sourceList.Skip(index).Take(itemsPerSet);
    }
}
于 2018-03-21T15:17:09.130 回答
12

我发现公认的答案(Serj-Tm)最强大,但我想建议一个通用版本。

public static List<List<T>> splitList<T>(List<T> locations, int nSize = 30)
{
    var list = new List<List<T>>();

    for (int i = 0; i < locations.Count; i += nSize)
    {
        list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i)));
    }

    return list;
}
于 2016-05-08T10:23:33.097 回答
9

尽管上面的许多答案都可以完成工作,但它们都在永无止境的序列(或非常长的序列)上失败了。以下是一个完全在线的实现,它保证了可能的最佳时间和内存复杂性。我们只迭代源可枚举一次并使用 yield return 进行惰性评估。消费者可以在每次迭代时丢弃列表,使内存占用等于列表batchSize的元素数量。

public static IEnumerable<List<T>> BatchBy<T>(this IEnumerable<T> enumerable, int batchSize)
{
    using (var enumerator = enumerable.GetEnumerator())
    {
        List<T> list = null;
        while (enumerator.MoveNext())
        {
            if (list == null)
            {
                list = new List<T> {enumerator.Current};
            }
            else if (list.Count < batchSize)
            {
                list.Add(enumerator.Current);
            }
            else
            {
                yield return list;
                list = new List<T> {enumerator.Current};
            }
        }

        if (list?.Count > 0)
        {
            yield return list;
        }
    }
}

编辑:刚刚意识到 OP 要求将 aList<T>分解为 small List<T>,因此我关于无限可枚举的评论不适用于 OP,但可能会帮助到这里的其他人。这些评论是对其他已发布解决方案的回应,这些解决方案确实IEnumerable<T>用作其功能的输入,但多次枚举源可枚举。

于 2018-03-20T22:09:40.397 回答
9

最后加上非常有用的mhand评论

原始答案

尽管大多数解决方案可能有效,但我认为它们的效率不是很高。假设您只想要前几个块的前几个项目。那么你就不想遍历序列中的所有(无数)项目。

以下将最多列举两次:一次用于 Take,一次用于 Skip。它不会枚举比您将使用的元素更多的元素:

public static IEnumerable<IEnumerable<TSource>> ChunkBy<TSource>
    (this IEnumerable<TSource> source, int chunkSize)
{
    while (source.Any())                     // while there are elements left
    {   // still something to chunk:
        yield return source.Take(chunkSize); // return a chunk of chunkSize
        source = source.Skip(chunkSize);     // skip the returned chunk
    }
}

这将枚举序列多少次?

假设您将源分成chunkSize. 您仅枚举前 N 个块。从每个枚举块中,您只会枚举前 M 个元素。

While(source.Any())
{
     ...
}

Any 将获取 Enumerator,执行 1 MoveNext() 并在 Disposing Enumerator 后返回返回值。这将完成 N 次

yield return source.Take(chunkSize);

根据参考资料,这将执行以下操作:

public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count)
{
    return TakeIterator<TSource>(source, count);
}

static IEnumerable<TSource> TakeIterator<TSource>(IEnumerable<TSource> source, int count)
{
    foreach (TSource element in source)
    {
        yield return element;
        if (--count == 0) break;
    }
}

在您开始枚举获取的块之前,这并没有多大作用。如果您获取多个块,但决定不枚举第一个块,则不会执行 foreach,因为您的调试器会向您显示。

如果你决定取第一个块的前 M 个元素,那么 yield return 将被执行 M 次。这表示:

  • 获取枚举器
  • 调用 MoveNext() 和 Current M 次。
  • 释放枚举器

在第一个块被 yield 返回后,我们跳过这个第一个块:

source = source.Skip(chunkSize);

再一次:我们将查看参考源以找到skipiterator

static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count)
{
    using (IEnumerator<TSource> e = source.GetEnumerator()) 
    {
        while (count > 0 && e.MoveNext()) count--;
        if (count <= 0) 
        {
            while (e.MoveNext()) yield return e.Current;
        }
    }
}

如您所见,对 Chunk 中的每个元素SkipIterator调用MoveNext()一次。它不叫Current

因此,对于每个 Chunk,我们看到已完成以下操作:

  • 任何():GetEnumerator;1 移动下一个();处置枚举器;
  • 拿():

    • 如果没有枚举块的内容,则什么都没有。
    • 如果枚举内容:GetEnumerator(),每个枚举项一个 MoveNext 和一个 Current,Dispose 枚举器;

    • Skip():对于每个被枚举的块(不是块的内容):GetEnumerator(),MoveNext() chunkSize 次,没有 Current!处置枚举器

如果您查看枚举器发生的情况,您会发现有很多对 MoveNext() 的调用,并且只对Current您实际决定访问的 TSource 项进行调用。

如果你取 N 个大小为 chunkSize 的块,则调用 MoveNext()

  • Any() N 次
  • 还没有任何时间 Take,只要你不枚举块
  • Skip() 的 N 倍 chunkSize

如果您决定仅枚举每个获取的块的前 M 个元素,那么您需要对每个枚举的块调用 MoveNext M 次。

总数

MoveNext calls: N + N*M + N*chunkSize
Current calls: N*M; (only the items you really access)

因此,如果您决定枚举所有块的所有元素:

MoveNext: numberOfChunks + all elements + all elements = about twice the sequence
Current: every item is accessed exactly once

MoveNext 是否需要大量工作,取决于源序列的类型。对于列表和数组,它是一个简单的索引增量,可能还有一个超出范围的检查。

但是如果你的 IEnumerable 是数据库查询的结果,请确保数据确实在你的计算机上物化,否则数据将被多次获取。DbContext 和 Dapper 会在数据被访问之前正确地将数据传输到本地进程。如果您多次枚举相同的序列,则不会多次获取它。Dapper 返回一个 List 对象,DbContext 记得数据已经被获取。

在开始划分块中的项目之前调用 AsEnumerable() 或 ToLists() 是否明智取决于您的存储库

于 2018-02-01T16:21:47.017 回答
8

我有一个通用方法,可以采用任何类型,包括浮点数,并且已经过单元测试,希望对您有所帮助:

    /// <summary>
    /// Breaks the list into groups with each group containing no more than the specified group size
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="values">The values.</param>
    /// <param name="groupSize">Size of the group.</param>
    /// <returns></returns>
    public static List<List<T>> SplitList<T>(IEnumerable<T> values, int groupSize, int? maxCount = null)
    {
        List<List<T>> result = new List<List<T>>();
        // Quick and special scenario
        if (values.Count() <= groupSize)
        {
            result.Add(values.ToList());
        }
        else
        {
            List<T> valueList = values.ToList();
            int startIndex = 0;
            int count = valueList.Count;
            int elementCount = 0;

            while (startIndex < count && (!maxCount.HasValue || (maxCount.HasValue && startIndex < maxCount)))
            {
                elementCount = (startIndex + groupSize > count) ? count - startIndex : groupSize;
                result.Add(valueList.GetRange(startIndex, elementCount));
                startIndex += elementCount;
            }
        }


        return result;
    }
于 2012-07-13T03:39:48.843 回答
3
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int maxItems)
{
    return items.Select((item, index) => new { item, index })
                .GroupBy(x => x.index / maxItems)
                .Select(g => g.Select(x => x.item));
}
于 2018-09-17T20:22:54.880 回答
3

从 .NET 6.0 开始,您可以使用 LINQ 扩展Chunk<T>()将枚举拆分为块。文档

var chars = new List<char>() { 'h', 'e', 'l', 'l', 'o', 'w','o','r' ,'l','d' };
foreach (var batch in chars.Chunk(2))
{
    foreach (var ch in batch)
    {
        // iterates 2 letters at a time
    }
}
于 2021-08-05T06:15:16.033 回答
2

这个怎么样?这个想法是只使用一个循环。而且,谁知道呢,也许您在代码中只使用 IList 实现,并且您不想强制转换为 List。

private IEnumerable<IList<T>> SplitList<T>(IList<T> list, int totalChunks)
{
    IList<T> auxList = new List<T>();
    int totalItems = list.Count();

    if (totalChunks <= 0)
    {
        yield return auxList;
    }
    else 
    {
        for (int i = 0; i < totalItems; i++)
        {               
            auxList.Add(list[i]);           

            if ((i + 1) % totalChunks == 0)
            {
                yield return auxList;
                auxList = new List<T>();                
            }

            else if (i == totalItems - 1)
            {
                yield return auxList;
            }
        }
    }   
}
于 2019-06-05T16:00:46.987 回答
1

多一个

public static IList<IList<T>> SplitList<T>(this IList<T> list, int chunkSize)
{
    var chunks = new List<IList<T>>();
    List<T> chunk = null;
    for (var i = 0; i < list.Count; i++)
    {
        if (i % chunkSize == 0)
        {
            chunk = new List<T>(chunkSize);
            chunks.Add(chunk);
        }
        chunk.Add(list[i]);
    }
    return chunks;
}
于 2019-07-25T14:58:50.850 回答
1

在 .NET 6 中,您可以使用source.Chunk(chunkSize)

基于 Serj-Tm 接受的答案的更通用的版本。

    public static IEnumerable<IEnumerable<T>> Split<T>(IEnumerable<T> source, int size = 30)
    {
        var count = source.Count();
        for (int i = 0; i < count; i += size)
        {
            yield return source
                .Skip(Math.Min(size, count - i))
                .Take(size);
        }
    }
于 2021-04-22T10:53:34.953 回答
1
public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize)
    {           
        var result = new List<List<T>>();
        for (int i = 0; i < source.Count; i += chunkSize)
        {
            var rows = new List<T>();
            for (int j = i; j < i + chunkSize; j++)
            {
                if (j >= source.Count) break;
                rows.Add(source[j]);
            }
            result.Add(rows);
        }
        return result;
    }
于 2019-08-16T13:34:52.667 回答
0

您可以仅使用 LINQ 简单地尝试以下代码:

public static IList<IList<T>> Split<T>(IList<T> source)
{
    return  source
        .Select((x, i) => new { Index = i, Value = x })
        .GroupBy(x => x.Index / 3)
        .Select(x => x.Select(v => v.Value).ToList())
        .ToList();
}
于 2021-08-14T04:31:29.977 回答
0

基于Dimitry Pavlov answere我将删除.ToList(). 并且还要避免匿名类。相反,我喜欢使用不需要堆内存分配的结构。(AValueTuple也可以工作。)

public static IEnumerable<IEnumerable<TSource>> ChunkBy<TSource>(this IEnumerable<TSource> source, int chunkSize)
{
    if (source is null)
    {
        throw new ArgumentNullException(nameof(source));
    }
    if (chunkSize <= 0)
    {
        throw new ArgumentOutOfRangeException(nameof(chunkSize), chunkSize, "The argument must be greater than zero.");
    }

    return source
        .Select((x, i) => new ChunkedValue<TSource>(x, i / chunkSize))
        .GroupBy(cv => cv.ChunkIndex)
        .Select(g => g.Select(cv => cv.Value));
} 

[StructLayout(LayoutKind.Auto)]
[DebuggerDisplay("{" + nameof(ChunkedValue<T>.ChunkIndex) + "}: {" + nameof(ChunkedValue<T>.Value) + "}")]
private struct ChunkedValue<T>
{
    public ChunkedValue(T value, int chunkIndex)
    {
        this.ChunkIndex = chunkIndex;
        this.Value = value;
    }

    public int ChunkIndex { get; }

    public T Value { get; }
}

这可以像下面这样使用,它只迭代一次集合,也不分配任何重要的内存。

int chunkSize = 30;
foreach (var chunk in collection.ChunkBy(chunkSize))
{
    foreach (var item in chunk)
    {
        // your code for item here.
    }
}

如果实际上需要一个具体的列表,那么我会这样做:

int chunkSize = 30;
var chunkList = new List<List<T>>();
foreach (var chunk in collection.ChunkBy(chunkSize))
{
    // create a list with the correct capacity to be able to contain one chunk
    // to avoid the resizing (additional memory allocation and memory copy) within the List<T>.
    var list = new List<T>(chunkSize);
    list.AddRange(chunk);
    chunkList.Add(list);
}
于 2020-06-05T07:22:06.750 回答
0

我遇到了同样的需求,我结合使用了 Linq 的Skip()Take()方法。我将我取的数字乘以到目前为止的迭代次数,这给了我要跳过的项目数,然后我选择下一组。

        var categories = Properties.Settings.Default.MovementStatsCategories;
        var items = summariesWithinYear
            .Select(s =>  s.sku).Distinct().ToList();

        //need to run by chunks of 10,000
        var count = items.Count;
        var counter = 0;
        var numToTake = 10000;

        while (count > 0)
        {
            var itemsChunk = items.Skip(numToTake * counter).Take(numToTake).ToList();
            counter += 1;

            MovementHistoryUtilities.RecordMovementHistoryStatsBulk(itemsChunk, categories, nLogger);

            count -= numToTake;
        }
于 2020-04-02T12:58:10.500 回答
0
List<int> orginalList =new List<int>(){1,2,3,4,5,6,7,8,9,10,12};
Dictionary<int,List<int>> dic = new Dictionary <int,List<int>> ();
int batchcount = orginalList.Count/2; //To List into two 2 parts if you 
 want three give three
List<int> lst = new List<int>();
for (int i=0;i<orginalList.Count; i++)
{
lst.Add(orginalList[i]);
if (i % batchCount == 0 && i!=0)
{
Dic.Add(threadId, lst);
lst = new List<int>();**strong text**
threadId++;
}
}
if(lst.Count>0)
Dic.Add(threadId, lst); //in case if any dayleft 
foreach(int BatchId in Dic.Keys)
{
  Console.Writeline("BatchId:"+BatchId);
  Console.Writeline('Batch Count:"+Dic[BatchId].Count);
}
于 2020-01-28T09:08:54.227 回答
-1

如果你想用条件而不是固定数字分割它:

///<summary>
/// splits a list based on a condition (similar to the split function for strings)
///</summary>
public static IEnumerable<List<T>> Split<T>(this IEnumerable<T> src, Func<T, bool> pred)
{
    var list = new List<T>();
    foreach(T item in src)
    {   
        if(pred(item))
        {
            if(list != null && list.Count > 0)
                yield return list;
                
            list = new List<T>();
        }
        else
        {
            list.Add(item);
        }
    }
}
于 2021-06-07T12:38:03.690 回答