0

我有这个:

string[] old = new string[] {"a","b","c","d"};

表示二维数组列的值:

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;
4

2 回答 2

1

我将为锯齿状数组执行此操作,因为它更容易,并且在两者之间来回切换是一个已解决的问题。

妙语是这样的,很简单:

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]);
    }
}
于 2013-08-03T02:11:29.353 回答
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()
于 2013-08-03T02:15:55.590 回答