我认为接受的答案很棒。可以使用匿名类型,如该答案所示,或者声明一个命名类型以在排序时保存数据。
更好的是,声明一个命名类型来保存数据所有时间。并行数组通常不是一个好主意。出于性能或互操作性的原因,在某些小众场景中需要它们,否则应避免使用。
也就是说,为了完整起见,我认为还指出可以“通过代理”对数组进行排序会很有用。 IE。创建一个新数组,它只是原始数组的索引并对 that 数组进行排序。索引数组排序后,您可以使用该数组直接访问原始数据,也可以使用该数组将原始数据复制到新的排序数组中。
例如:
static void Main(string[] args)
{
int[] values = { 10, 20, 20, 10, 30 };
int[] keys = { 1, 2, 3, 4, 5 };
int[] indexes = Enumerable.Range(0, values.Length).ToArray();
Array.Sort(indexes, (i1, i2) => Compare(i1, i2, values, keys));
// Use the index array directly to access the original data
for (int i = 0; i < values.Length; i++)
{
Console.WriteLine("{0}: {1}", values[indexes[i]], keys[indexes[i]]);
}
Console.WriteLine();
// Or go ahead and copy the old data into new arrays using the new order
values = OrderArray(values, indexes);
keys = OrderArray(keys, indexes);
for (int i = 0; i < values.Length; i++)
{
Console.WriteLine("{0}: {1}", values[i], keys[i]);
}
}
private static int Compare(int i1, int i2, int[] values, int[] keys)
{
int result = values[i1].CompareTo(values[i2]);
if (result == 0)
{
result = keys[i1].CompareTo(keys[i2]);
}
return result;
}
private static int[] OrderArray(int[] values, int[] indexes)
{
int[] result = new int[values.Length];
for (int i = 0; i < values.Length; i++)
{
result[i] = values[indexes[i]];
}
return result;
}