【发布时间】: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