Reputation: 15477
i have 3 generic dictionaries
static void Main(string[] args)
{
Dictionary<string, string> input = new Dictionary<string, string>();
input.Add("KEY1", "Key1");
Dictionary<string, string> compare = new Dictionary<string, string>();
compare.Add("KEY1", "Key1");
compare.Add("KEY2", "Key2");
compare.Add("KEY3", "Key3");
Dictionary<string, string> results = new Dictionary<string, string>();
i'd like to take the list of input and compare each value to the compareTo list and if it doesn't exist add it to the results list?
Upvotes: 1
Views: 333
Reputation: 38417
You can use the LINQ Except() method:
foreach (var pair in compare.Except(input))
{
results[pair.Key] = pair.Value;
}
This will perform a set difference (in effect subtracting input
from compare
and returning what is left over), which we can then add to the results
dictionary.
Now, if results
has no previous values, and you just want it to be the results
from that current operation, you can just do that directly:
var results = compare.Except(input)
.ToDictionary(pair => pair.Key, pair => pair.Value);
This is assuming you want the difference in keys and values. If you had a different value (same key), it would show in the difference.
That is, for your example above results will have:
[KEY2, Key2]
[KEY3, Key3]
But if your example data was:
Dictionary<string, string> input = new Dictionary<string, string>();
input.Add("KEY1", "Key1");
Dictionary<string, string> compare = new Dictionary<string, string>();
compare.Add("KEY1", "X");
compare.Add("KEY2", "Key2");
compare.Add("KEY3", "Key3");
The results would be:
[KEY1, X]
[KEY2, Key2]
[KEY3, Key3]
Due to the fact KEY1's value was different.
If you do want only where keys or values are not contained in the other, you can do the Except
on the Keys
or Values
collections of the dictionary instead.
Upvotes: 2
Reputation: 22389
dict[key]
gives you the value whose key is key
.
dict.ContainsKey(key)
and dict.ContainsValue(value)
are methods you can use to check whether a key or a value are in the dictionary. ContainsKey
is more time-efficient.
Upvotes: 1