Search code examples
c#listdictionarymatchequality

C#: Intersect a dictionary with a list. Return dictionary item after match


how can I safety return the dictionary item which matches with the item from the list?

static void Test()
{
    var dict = new Dictionary<string, string>();
    dict.Add("license1", "123");
    dict.Add("license2", "456");
    dict.Add("license3", "789");

    var list = new List<string>();
    list.Add("444");
    list.Add("111");
    list.Add("123");

    var result = dict.Values.Intersect(list);
    //result should be only the matching item as a dictionary for dict -> for this example = "license1, 123"
}

Solution

  • Because the dictionary isn't arranged helpfully I think I might do:

    var h = list.ToHashSet();
    var result = dict.Where(kvp => h.Contains(kvp.Value));