Compare items in different dictionaries with one key using LINQ

I have two dictionaries with a string key and different types of values.

private Dictionary<string, IProperty> _properties; private Dictionary<string, Expectation> _expectations; 

I need to compare the elements sharing the same key and get the corresponding expectations. Here is my method signature in the wait class.

 public bool Matches(IProperty property) 

How to do it with LINQ?

+4
source share
4 answers
 var result = _expectations.Where(e => _properties.Any(p => p.Key == e.Key && e.Value.Matches(p.Value))); 
+4
source

If you understood correctly,

You can internally join both collections and then return the value

 var exp = form p in _properties join e in _expectations on p.key equals e.key select e; 

for details you can check this image: enter image description here

+5
source
 var result = from pKey in _properties.Keys where _expectations.ContainsKey(pKey) let e = _expectations[pKey] select e; 

This is more efficient than combining, because it uses key searching in _expectations . It could be improved a bit using this extension method:

 public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) where TValue : class { TValue value; if (dictionary.TryGetValue(key, out value)) return value; return null; } var result = from pKey in _properties.Keys let e = _expectations.GetValueOrDefault(pKey) where e != null select e; 

(he avoids searching for the key twice)

+4
source
 var matches = _expectations.Where( kvp => _properties.ContainsKey(kvp.Key) && kvp.Value.Matches(_properties[kvp.Key])); 

If you know that the key exists in both dictionaries, you can also remove the ContainsKey check:

 var matches = _expectations.Where(kvp => kvp.Value.Matches(_properties[kvp.Key])); 

As a result of the above, there will be KeyValuePairs. To get right on hold, simply add .Select(kvp => kvp.Value) to the selection method above.

0
source

All Articles