用对应关系重新排序不同类型的数组
本文关键字:排序 同类型 数组 关系 新排序 | 更新日期: 2023-09-27 18:25:57
我有这个:
string[] old = new string[] {"a","b","c","d"};
表示2D阵列列的值:
double[,] values = new double[,] {{1,2,3,4},{5,6,7,8},{1,3,5,9}};
如何使用linq重新排序这个2D数组的列将字符串数组值重新排序为
string[] newer = new string[] {"c","a","d","b"};
我使用辅助int数组来保留新索引,但我希望使用LINQ!:)
int[] aux = new int[old.Length];
for (int i = 0; i < newer.Length; i++)
{
for (int j = 0; j < old.Length; j++)
{
if (old[j] == newer[i])
{
aux[i] = j;
}
}
}
double[,] newvalues = new double[values.GetLength(0), values.GetLength(1)];
for (int i = 0; i < values.GetLength(0); i++)
{
for (int j = 0; j < values.GetLength(1); j++)
{
newvalues[i, j] = values[i, aux[j]];
}
}
values = newvalues;
我将对锯齿状数组执行此操作,因为这更容易,并且在两者之间来回切换是一个已解决的问题。
笑点是,它很简单:
Array.Sort(keys, doubles, new CustomStringComparer(reorderedKeys));
以下是使其工作的设置:
var doubles =
new double[][] {
new double[] {1, 2, 3, 4},
new double[] {5, 6, 7, 8},
new double[] {1, 3, 5, 7},
new double[] {2, 4, 6, 8}
};
var keys = new [] { "a", "b", "c", "d" };
var reorderedKeys = new [] { "c", "a", "d", "b" };
这里,我使用:
class CustomStringComparer : IComparer<string> {
Dictionary<string, int> ranks;
public CustomStringComparator(string[] reorderedKeys) {
ranks = reorderedKeys
.Select((value, rank) => new { Value = value, Rank = rank })
.ToDictionary(x => x.Value, x => x.Rank);
}
public int Compare(string x, string y) {
return ranks[x].CompareTo(ranks[y]);
}
}
不能将多维数组与Linq一起使用,因为它们没有实现IEnumerable<T>
。如果您选择使用锯齿状阵列:
double[][] values = new double[][] {
new double[]{1,2,3,4},
new double[]{5,6,7,8},
new double[]{1,3,5,9}};
//...
newer
.Join(
old.Zip(values, (key, val) => new{key, val}),
a => a,
b => b.key,
(a, b) => b.val)
.ToArray()