是否有任何方法可以将List<SomeObject>分离为SomeObject的几个单独的列表,使用项目索引作为每个分割的分隔符?

让我举个例子:

我有一个List<SomeObject>,我需要一个List<List<SomeObject>>或List<SomeObject>[],这样每个结果列表将包含一组原始列表的3个项目(依次)。

eg.:

原始列表:[a, g, e, w, p, s, q, f, x, y, i, m, c] 结果列表:[a、g e], [w、p, s], [q, f, x]、[y,我,m], [c]

我还需要结果列表的大小是这个函数的参数。


当前回答

对于任何对打包/维护解决方案感兴趣的人来说,MoreLINQ库提供了符合您所请求行为的批处理扩展方法:

IEnumerable<char> source = "Example string";
IEnumerable<IEnumerable<char>> chunksOfThreeChars = source.Batch(3);

批处理实现类似于Cameron MacFarland的答案,在返回之前添加了用于转换块/批处理的重载,并且性能相当好。

其他回答

我刚刚写了这个,我认为它比其他提出的解决方案更优雅一点:

/// <summary>
/// Break a list of items into chunks of a specific size
/// </summary>
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunksize)
{
    while (source.Any())
    {
        yield return source.Take(chunksize);
        source = source.Skip(chunksize);
    }
}

如果列表的类型为system.collections.generic,则可以使用“CopyTo”方法将数组中的元素复制到其他子数组中。您可以指定开始元素和要复制的元素数量。

你也可以对你的原始列表做3个克隆,并在每个列表上使用“RemoveRange”将列表缩小到你想要的大小。

或者只是创建一个helper方法来为您做这件事。

从。net 6开始,你现在可以使用原生Chunk()方法,可用于IEnumerable<T>和IQueryable<T>。

更多信息(和链接)在这里:https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/partitioning-data

对于任何对打包/维护解决方案感兴趣的人来说,MoreLINQ库提供了符合您所请求行为的批处理扩展方法:

IEnumerable<char> source = "Example string";
IEnumerable<IEnumerable<char>> chunksOfThreeChars = source.Batch(3);

批处理实现类似于Cameron MacFarland的答案,在返回之前添加了用于转换块/批处理的重载,并且性能相当好。

使用模块化分区:

public IEnumerable<IEnumerable<string>> Split(IEnumerable<string> input, int chunkSize)
{
    var chunks = (int)Math.Ceiling((double)input.Count() / (double)chunkSize);
    return Enumerable.Range(0, chunks).Select(id => input.Where(s => s.GetHashCode() % chunks == id));
}