Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare items in different dictionaries with same key using LINQ

Tags:

c#

.net

linq

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?

like image 462
Ufuk Hacıoğulları Avatar asked Dec 06 '22 20:12

Ufuk Hacıoğulları


2 Answers

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)

like image 68
Thomas Levesque Avatar answered Dec 10 '22 02:12

Thomas Levesque


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 : enter image description here

like image 32
Pranay Rana Avatar answered Dec 10 '22 02:12

Pranay Rana