对两个数组(值,键)进行排序,然后对键进行排序

Ken*_* Ma 3 c# arrays

我有一个似乎是一个简单的问题,但到目前为止我无法弄明白.

说我有两个数组:

int[] values = {10,20,20,10,30};
int[] keys = {1,2,3,4,5};

Array.Sort(values,keys);
Run Code Online (Sandbox Code Playgroud)

然后数组看起来像这样:

values = {10,10,20,20,30};
keys = {4,1,2,3,5};
Run Code Online (Sandbox Code Playgroud)

现在,我想要做的是使键也以第二优先级排序,因此键数组看起来像这样:

keys = {1,4,2,3,5};
Run Code Online (Sandbox Code Playgroud)

请注意,切换了1和4值,并且值数组的顺序没有改变.

dig*_*All 6

如果您不是非常需要"就地排序",我建议使用OrderBy:

var sortedPairs = values.Select((x, i) => new { Value = x, Key = keys[i] })
                        .OrderBy(x => x.Value)
                        .ThenBy(x => x.Key)
                        .ToArray(); // this avoids sorting 2 times...
int[] sortedValues = sortedPairs.Select(x => x.Value).ToArray();
int[] sortedKeys = sortedPairs.Select(x => x.Key).ToArray();

// Result:
// sortedValues = {10,10,20,20,30};
// sortedKeys = {1,4,2,3,5};
Run Code Online (Sandbox Code Playgroud)