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

Time:10-04

so for example, this code here does the job fine for this specific task, but I really don't like how I need to reuse the loop 2 times to get the size and then implement the method, it feels not right.

      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;
        }

Is there anyway to get the size in the first loop and then implement the method, having no need of the second loop?

If you need to understand this particular task:

        /// <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>

CodePudding user response:

try this

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

output

 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
  • Related