C#:将字典与列表相交。匹配后返回字典项目

问题描述 投票:0回答:1

如何安全返回与列表中的项目匹配的字典项目?

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"
}
c# list dictionary match equality
1个回答
1
投票

因为字典的排列没有帮助,我想我可以这样做:

var h = list.ToHashSet();
var result = dict.Where(kvp => h.Contains(kvp.Value));
© www.soinside.com 2019 - 2024. All rights reserved.