문제

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 또는 확장 방법을 사용하여 방법을 찾도록 도와 주시겠습니까? 내말은: F 그리고 F, H:I 그리고 H:I, 등.

도움이 되었습니까?

해결책

순수한 LINQ/Extension Method 솔루션을 사용하려면 자신의 구현을 정의해야합니다. IEqualityComparer 배열/시퀀스의 경우. (내가 명백한 것을 놓치지 않는 한, 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();

도움이되기를 바랍니다.

다른 팁

먼저 정수 배열을 비교하는 방법이 필요합니다. 프레임 워크의 클래스와 함께 사용하려면 equailtytymparer를 만들어 그렇게합니다. 배열이 항상 정렬되면 구현하기가 쉽습니다.

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

}

이제 해시 세트에서 정수 배열을 키로 사용하여 고유 한 배열을 얻을 수 있습니다.

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

해시 세트는 단지 중복 값을 버리므로 이제 4 개의 정수 배열이 포함되어 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top