开发者

Compare items in different dictionaries with same key using LINQ

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

private Dictionary<string, IProperty> _propert开发者_StackOverflowies;
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 :

Compare items in different dictionaries with same key using LINQ


var result = _expectations.Where(e => _properties.Any(p => p.Key == e.Key && e.Value.Matches(p.Value)));


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 remove the ContainsKey check as well:

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

The result from the above will be KeyValuePairs. To get directly at the Expectations simply append .Select(kvp => kvp.Value) to the above method of choice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜