如果数组长度不确定,建议用泛型集合,下面是实现的代码:
/// <summary>
/// 如果数组长度不一定,建议用List
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] strNew = GetOdd(nums);
foreach (var item in strNew)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
public static int[] GetOdd(int[] nums)
{
List<int> oddList = new List<int>();//创建List存储不定长度的数组
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] % 2 != 0)
{
oddList.Add(nums[i]);
}
}
int[] numsNew = oddList.ToArray();
return numsNew;
} |