Search code examples
c#listlinqdictionarytuples

dictionaries to tuple list


Short question. Is there a way to do this with Linq or any other default solution?

Two dictionaries with same key but different values to a tuple list. The list should contain only values, where both dictionaries had a matching key.

public static List<Tuple<TOut1, TOut2>> ParseToTupleList<TKey, TOut1, TOut2>(
    IDictionary<TKey, TOut1> a,
    IDictionary<TKey, TOut2> b)
{
    var list = new List<Tuple<TOut1, TOut2>>(a.Count());

    foreach (var keyValue in a)
    {
        if (b.TryGetValue(keyValue.Key, out var bValue))
        {
            list.Add(new Tuple<TOut1, TOut2>(keyValue.Value, bValue));
        }
    }

    return list;
}

Solution

  • You could use a Where() instead of the if, and a Select() instead of the list.Add.

    return a
        .Where(aEntry => b.ContainsKey(aEntry.Key))
        .Select(aEntry => new Tuple<TOut1, TOut2>(aEntry.Value, b[aEntry.Key]))
        .ToList();
    

    Normally, "Contains" would be an O(n) operation, but with a dictionary it's O(1), so that's not a performance impact. You could also rewrite this to use a join instead, matching A's entry on B's entry by key.

    return (from aEntry in a
            join bEntry in b on aEntry.Key equals bEntry.Key
            select new Tuple<TOut1, TOut2>(aEntry.Value, bEntry.Value)).ToList();