C#没有像VB中那样可以定义动态数组,但有更加强大的ArrayList(),下面例子获取一组数据中的最大值,并且用ArrayList获取他们的在数列中的序号。
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Diagnostics;namespace debug
{
class Program
{
static int getMax(int[] numGroup, out ArrayList indices)
{
int maxValue;
indices = new ArrayList();
maxValue = numGroup[0];
int count=0;
foreach (int num in numGroup)
{
if (num>maxValue)
{
maxValue = num;
}
}
foreach (int num in numGroup)
{
if (num == maxValue)
{
indices.Add(count);
}
count++;
}
return maxValue;
}
static void Main(string[] args)
{
int[] myNumbers;
myNumbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 3, 4, 5, 6, 8, 0, 8, 9, 5, 3, 9 };
ArrayList indices;
indices = new ArrayList();
Console.WriteLine("The maximum value is {0}", getMax(myNumbers, out indices));
Console.Write("Their indices are");
foreach (object obj in indices)
{
Console.Write(" {0} ",obj);
}
Console.ReadKey();
}
}
}