2013-08-03 75 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