1

配列の配列があります。VSTOを使用したExcelでの選択に関する情報です。ここで、各要素は選択の開始位置と終了位置を意味します。

例えば、

int[][] selection = {
new int[] { 1 }, // column A
new int[] { 6 }, // column F
new int[] { 6 }, // column F
new int[] { 8, 9 } // columns H:I
new int[] { 8, 9 } // columns H:I
new int[] { 12, 15 } // columns L:O
};

重複した要素を削除する方法を見つけるのを手伝ってもらえますか?おそらくLINQまたはExtensionメソッドを使用しますか?つまり、、、、など。F_FH:IH:I

4

2 に答える 2

3

IEqualityComparer純粋なLINQ/拡張メソッドソリューションを使用する場合は、配列/シーケンスの独自の実装を定義する必要があります。(明らかな何かが欠けている場合を除いて、BCLには既存の配列またはシーケンス比較機能はありません)。ただし、これはそれほど難しいことではありません。これは、非常にうまく機能するはずの例です。

public class SequenceEqualityComparer<T> : IEqualityComparer<IEnumerable<T>>
{
    public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
    {
        return Enumerable.SequenceEqual(x, y);
    }

    // Probably not the best hash function for an ordered list, but it should do the job in most cases.
    public int GetHashCode(IEnumerable<T> obj)
    {
        int hash = 0;
        int i = 0;
        foreach (var element in obj)
            hash = unchecked((hash * 37 + hash) + (element.GetHashCode() << (i++ % 16)));
        return hash;
    }
}

これの利点は、以下を呼び出すだけで重複する配列を削除できることです。

var result = selection.Distinct(new SequenceEqualityComparer<int>()).ToArray();

お役に立てば幸いです。

于 2009-03-31T16:19:04.153 に答える
0

まず、整数配列を比較する方法が必要です。フレームワーク内のクラスでこれを使用するには、EquailtyComparer を作成します。配列が常にソートされている場合、実装はかなり簡単です。

public class IntArrayComparer : IEqualityComparer<int[]> {

    public bool Equals(int[] x, int[] y) {
        if (x.Length != y.Length) return false;
        for (int i = 0; i < x.Length; i++) {
            if (x[i] != y[i]) return false;
        }
        return true;
    }

    public int GetHashCode(int[] obj) {
        int code = 0;
        foreach (int value in obj) code ^= value;
        return code;
    }

}

HashSet のキーとして整数配列を使用して、一意の配列を取得できるようになりました。

int[][] selection = {
    new int[] { 1 }, // column A
    new int[] { 6 }, // column F
    new int[] { 6 }, // column F
    new int[] { 8, 9 }, // columns H:I
    new int[] { 8, 9 }, // columns H:I
    new int[] { 12, 15 } // columns L:O
};

HashSet<int[]> arrays = new HashSet<int[]>(new IntArrayComparer());
foreach (int[] array in selection) {
    arrays.Add(array);
}

HashSet は重複する値を破棄するだけなので、4 つの整数配列が含まれるようになりました。

于 2009-03-31T16:27:47.347 に答える