【问题标题】:C# how to save values from a array to a new array while not knowing the length of the new arrayC#如何在不知道新数组长度的情况下将数组中的值保存到新数组中
【发布时间】:2021-11-24 05:13:57
【问题描述】:

例如,这里的代码可以很好地完成这个特定任务,但我真的不喜欢我需要重复使用循环 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>

【问题讨论】:

    标签: c# arrays loops for-loop save


    【解决方案1】:

    试试这个

    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
    

    【讨论】:

    • 感谢您的回答,但我知道linq 可以更轻松地完成此特定任务。我正在寻找一种方法来保存新数组并暂时返回它而不使用两个类似的循环。
    • @Linascts 查看我的更新答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2013-07-18
    • 2018-02-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多