我有这个:
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重新排列此二维数组的列,将字符串数组值重新排序为
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;
答案 0 :(得分:1)
我要为锯齿状数组执行此操作,因为它更容易,并且在两者之间来回切换是solved问题。
这个妙语就是这个,很简单:
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]);
}
}
答案 1 :(得分:0)
您不能将多维数组与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()