在C#中将整数数组分割成多个整数数组的列表

3

我需要将一些Python代码转换成C#,但是其中的一部分让我感到困难。

def split_data(seq, length):
    return [seq[i:i + length] for i in range(0, len(seq), length)]

print(split_data([4,5,6,8,5],2))

这段代码的目的是接收一个int数组,并将其拆分为长度参数的多个子数组。例如,此处的打印结果将会是:[[4, 5], [6, 8], [5]] 问题是我需要在C#中实现相同的功能。所以我开始创建一个List<int[]>。我知道如何在其中添加int[],但我不知道如何像Python一样拆分它们,特别是使用这个长度参数。
我尝试使用for、foreach循环甚至IEnumerable来实现它,但都没有成功。
也许有一种非常简单的方法来完成它,或者是我还没有注意到的东西。我的C#知识水平也没有帮助我 :).
无论如何,感谢您的帮助。

可能是[在LINQ中创建批处理]的重复问题(https://dev59.com/42Yr5IYBdhLWcg3wXJEK)。 - Patrick Artner
其他重复问题:使用LINQ将列表拆分为子列表将IEnumerable<T>拆分为固定大小的块,返回一个IEnumerable<IEnumerable<T>>。请重新查看如何提问,并特别注意在提问之前进行研究 - 谢谢。 - Patrick Artner
2个回答

6
这里是使用yield return的解决方案: ```yield return```
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> seq, int length) {
    // figure out how many little sequences we need to create
    int count = seq.Count();
    int numberOfTimes = count % length == 0 ? count / length : count / length + 1;

    for (int i = 0 ; i < numberOfTimes ; i++) {
        yield return seq.Take(length);
        seq = seq.Skip(length);
    }
}

使用方法:

new int[] {1,2,3,4,5,6,7}.Split(2)

0

这应该可以解决问题。它是通用的,因此可以与任何数组一起使用,无论其类型如何。

/// <summary>
/// Splits an array into sub-arrays of a fixed length. The last entry will only be as long as the amount of elements inside it.
/// </summary>
/// <typeparam name="T">Type of the array</typeparam>
/// <param name="array">Array to split.</param>
/// <param name="splitLength">Amount of elements in each of the resulting arrays.</param>
/// <returns>An array of the split sub-arrays.</returns>
public static T[][] SplitArray<T>(T[] array, Int32 splitLength)
{
    List<T[]> fullList = new List<T[]>();
    Int32 remainder = array.Length % splitLength;
    Int32 last = array.Length - remainder;
    for (Int32 i = 0; i < array.Length; i += splitLength)
    {
        // Get the correct length in case this is the last one
        Int32 currLen = i == last ? remainder : splitLength;
        T[] currentArr = new T[currLen];
        Array.Copy(array, i, currentArr, 0, currLen);
        fullList.Add(currentArr);
    }
    return fullList.ToArray();
}

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