2013-08-03 84 views
0

我有这样的:重新排列不同类型的阵列与对应

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 reoder这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; 
+1

它必须在矩形的[[,]'数组上,还是可以在锯齿形的[] []'数组上? – jason

+0

矩形,我修正了代码...'newvalues [i,j] = values [i,aux [j]];' – user1204

+0

很好,两者之间的转换很容易。 – jason

回答

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]); 
    } 
} 
0

你可以用” t使用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() 
+0

由于尺寸不匹配,这不起作用...您(与我的答案相同)假定4 * 3'values'数组,而它是3 * 4并且第一维(3)与“old”的长度不匹配。 –

+0

@AlexeiLevenkov:邪恶的原始海报改变了他们的问题。原始版本有4 * 3 – spender