programing

교차()의 반대쪽

golfzon 2023. 5. 4. 20:50
반응형

교차()의 반대쪽

다음과 같이 교차를 사용하여 두 컬렉션 간의 일치 항목을 찾을 수 있습니다.

// Assign two arrays.
int[] array1 = { 1, 2, 3 };
int[] array2 = { 2, 3, 4 };
// Call Intersect extension method.
var intersect = array1.Intersect(array2);
// Write intersection to screen.
foreach (int value in intersect)
{
    Console.WriteLine(value); // Output: 2, 3
}

그러나 제가 달성하고자 하는 것은 반대입니다. 한 컬렉션에서 다른 컬렉션에서 누락된 항목을 나열하고 싶습니다.

// Assign two arrays.
int[] array1 = { 1, 2, 3 };
int[] array2 = { 2, 3, 4 };
// Call "NonIntersect" extension method.
var intersect = array1.NonIntersect(array2); // I've made up the NonIntersect method
// Write intersection to screen.
foreach (int value in intersect)
{
    Console.WriteLine(value); // Output: 4
}

위에서 설명한 바와 같이, 결과적으로 4를 얻고자 하는 경우 다음과 같이 할 수 있습니다.

var nonintersect = array2.Except(array1);

실제 비교차로(1과 4 모두)를 사용하려면 다음과 같이 해야 합니다.

var nonintersect = array1.Except(array2).Union( array2.Except(array1));

이것이 가장 성능이 좋은 솔루션은 아니지만 소규모 목록의 경우에는 잘 작동할 것입니다.

사용할 수 있습니다.

a.Except(b).Union(b.Except(a));

또는 사용할 수 있습니다.

var difference = new HashSet(a);
difference.SymmetricExceptWith(b);

이 코드는 각 시퀀스를 한 번만 열거하고 다음을 사용합니다.Select(x => x)결과를 숨기고 깨끗한 Linq 스타일 확장 메서드를 가져옵니다.사용하기 때문에HashSet<T>그것의 런타임은O(n + m)해시가 잘 분포되어 있는 경우두 목록 중 하나에 중복된 요소가 누락되었습니다.

public static IEnumerable<T> SymmetricExcept<T>(this IEnumerable<T> seq1,
    IEnumerable<T> seq2)
{
    HashSet<T> hashSet = new HashSet<T>(seq1);
    hashSet.SymmetricExceptWith(seq2);
    return hashSet.Select(x => x);
}

제 생각엔 당신이 찾고 있는 것 같습니다.Except:

예외 연산자는 두 시퀀스 간의 설정 차이를 생성합니다.두 번째 순서에는 나타나지 않는 첫 번째 순서의 요소만 반환됩니다.선택적으로 고유한 동등성 비교 함수를 제공할 수 있습니다.

자세한 내용은 이 링크, 이 링크 또는 Google을 확인하십시오.

배열 1.비교차(배열 2);

교차하지 않는 연산자는 Linq에 없습니다. 이렇게 해야 합니다.

제외 -> 조합 -> 제외

a.except(b).union(b.Except(a));

나는 당신의 비교차 방법이 (집합 이론과 관련하여) 무엇을 해야 하는지 100% 확신할 수 없습니다.
B \ A (A에서 발생하지 않는 B의 모든 것)?
예를 들어, 예외 연산(B)을 사용할 수 있습니다.(A)를 제외합니다.

/// <summary>
/// Given two list, compare and extract differences
/// http://stackoverflow.com/questions/5620266/the-opposite-of-intersect
/// </summary>
public class CompareList
{
    /// <summary>
    /// Returns list of items that are in initial but not in final list.
    /// </summary>
    /// <param name="listA"></param>
    /// <param name="listB"></param>
    /// <returns></returns>
    public static IEnumerable<string> NonIntersect(
        List<string> initial, List<string> final)
    {
        //subtracts the content of initial from final
        //assumes that final.length < initial.length
        return initial.Except(final);
    }

    /// <summary>
    /// Returns the symmetric difference between the two list.
    /// http://en.wikipedia.org/wiki/Symmetric_difference
    /// </summary>
    /// <param name="initial"></param>
    /// <param name="final"></param>
    /// <returns></returns>
    public static IEnumerable<string> SymmetricDifference(
        List<string> initial, List<string> final)
    {
        IEnumerable<string> setA = NonIntersect(final, initial);
        IEnumerable<string> setB = NonIntersect(initial, final);
        // sum and return the two set.
        return setA.Concat(setB);
    }
}
string left = "411329_SOFT_MAC_GREEN";
string right= "SOFT_MAC_GREEN";

string[] l = left.Split('_');
string[] r = right.Split('_');

string[] distinctLeft = l.Distinct().ToArray();
string[] distinctRight = r.Distinct().ToArray();

var commonWord = l.Except(r, StringComparer.OrdinalIgnoreCase)
string result = String.Join("_",commonWord);
result = "411329"

언급URL : https://stackoverflow.com/questions/5620266/the-opposite-of-intersect

반응형