C# 如何在不知道新数组长度的情况下将数组中的值保存到新数组

C# how to save values from a array to a new array while not knowing the length of the new array

所以例如,这段代码可以很好地完成这个特定任务,但我真的不喜欢我需要重复使用循环 2 次来获取大小然后实现方法,感觉不是对了。

      public static int[] FilterByDigit(int[] source, int digit)
        {
            int size = 0;

            for (int i = 0; i < source.Length; i++)
            {
                bool result = source[i].ToString().Contains(digit.ToString());

                if (result)
                {
                    size++;
                }
            }

            int[] arr = new int[size];
            int count = 0;

            for (int i = 0; i < source.Length; i++)
            {
                bool result = source[i].ToString().Contains(digit.ToString());

                if (result)
                {
                    arr[count] = source[i];
                    count++;
                }
            }

            return arr;
        }

有没有在第一个循环中获取大小然后实现方法,而不需要第二个循环?

如果您需要了解此特定任务:

        /// <summary>
        /// Returns new array of elements that contain expected digit from source array.
        /// </summary>
        /// <param name="source">Source array.</param>
        /// <param name="digit">Expected digit.</param>
        /// <returns>Array of elements that contain expected digit.</returns>
        /// <exception cref="ArgumentNullException">Thrown when array is null.</exception>
        /// <exception cref="ArgumentException">Thrown when array is empty.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when digit value is out of range (0..9).</exception>
        /// <example>
        /// {1, 2, 3, 4, 5, 6, 7, 68, 69, 70, 15, 17}  => { 7, 70, 17 } for digit = 7.
        /// </example>

试试这个

public static int[] FilterByDigit(int[] source, int digit)
  {
    return source.Where(s => s.ToString().Contains(digit.ToString()));
}

输出

 int digit=7;
  var source = new int[] {1, 2, 3, 4, 5, 6, 7, 68, 69, 70, 15, 17};
  var result =FilterByDigit(source,digit);
 var output=string.Join(",",result);
    
7,70,17