I have two dictionaries with a string key and different value types.
private Dictionary<string, IProperty> _properties;
private Dictionary<string, Expectation> _expectations;
I need to compare elements sharing same key and get matching Expectations. Here's my method signature in Expectation class.
public bool Matches(IProperty property)
How can I do that using LINQ?
var result = from pKey in _properties.Keys
where _expectations.ContainsKey(pKey)
let e = _expectations[pKey]
select e;
It's more efficient than a join, because it takes advantage of the key lookup in _expectations
. It could be slightly improved by using an extension method like that:
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;
(it avoids looking up the key twice)
If i get you correctly,
You can inner join both of the collection and than get value back
var exp = form p in _properties
join e in _expectations
on p.key equals e.key
select e;
for detail youcan check this image :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With