Comparison of two sets for new and missing keys

When comparing two sets of vocabulary character in C #: set A and set B, what is the best way to list keys that are in set A but not in set B and vice versa?

For instance:

A = { 1, 2, 5 }
B = { 2, 3, 5 }

Comparison B with A, missing keys = {1} and new keys = {3}.

Using objects Dictionary<...,...>, you can list all the values ​​in B and test using set A with A.ContainsKey(key);, but it seems like there should be a better way that a sorted set could include?

+5
source share
4 answers

I know two built-in ways to make given differences.

1) Enumerable.Except

.

:

IEnumerable<int> a = new int[] { 1, 2, 5 };
IEnumerable<int> b = new int[] { 2, 3, 5 };

foreach (int x in a.Except(b))
{
    Console.WriteLine(x);  // prints "1"
}

2a) HashSet <T> .ExceptWith

HashSet <T> .

HashSet<int> a = new HashSet<int> { 1, 2, 5 };
HashSet<int> b = new HashSet<int> { 2, 3, 5 };

a.ExceptWith(b);

foreach (int x in a)
{
    Console.WriteLine(x);  // prints "1"
}

2b) HashSet <T> .SymmetricExceptWith

HashSet <T> , , , .

HashSet<int> a = new HashSet<int> { 1, 2, 5 };
HashSet<int> b = new HashSet<int> { 2, 3, 5 };

a.SymmetricExceptWith(b);

foreach (int x in a)
{
    Console.WriteLine(x);  // prints "1" and "3"
}

- , , , .

+7

SortedDictionary: A.Except(A.Intersect(B)).

, , .

+2

Except.

Dictionary<string, string> dic1 = new Dictionary<string, string>() { { "rabbit", "hat" }, { "frog", "pond" }, { "cat", "house" } };
Dictionary<string, string> dic2 = new Dictionary<string, string>() { { "rabbit", "hat" }, { "dog", "house"}, {"cat", "garden"}};

    var uniqueKeys = dic1.Keys.Except(dic2.Keys);

    foreach (var item in uniqueKeys)
    {
        Console.WriteLine(item);
    }
0

, , . :

Q) #: A B, , A, B ? Dictionary <...,... > , B A, A.ContainsKey(key);,...

, . - , , .

Q)... , , ?

, . , BinarySearch, 1 2 ect.

See SetList Complement and Subtract operations: http://csharptest.net/browse/src/Library/Collections/SetList.cs#234

0
source

All Articles