【问题标题】:Spliting an int array into a list of several int arrays in C#在 C# 中将一个 int 数组拆分为几个 int 数组的列表
【发布时间】:2018-04-23 10:16:20
【问题描述】:

我必须将一些代码从 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# 的了解不足也对我没有帮助:)。

感谢您的帮助。

【问题讨论】:

标签: c# python arrays


【解决方案1】:

这是使用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)

【讨论】:

    【解决方案2】:

    应该这样做。它是通用的,因此它应该适用于任何数组,无论它是哪种类型。

    /// <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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-23
      • 2023-03-04
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 2012-05-28
      • 1970-01-01
      • 2014-07-18
      相关资源
      最近更新 更多