我有两个字典A和B,想要从字典A中搜索一个值到字典B

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

我有两个字典 A 和 B,想要从字典 A 中搜索一个值到字典 B 中。 输出将保存到字典 C 中。

我尝试使用以下 C# 代码进行编译,但不知何故无法搜索字典 B 中的值(即使该值存在于字典 B 中)

     Dictionary<string, List<string>> A = new Dictionary<string, List<string>>();
     // Key:Values are stored in dictionary A
     A.Add(..,..)
     Dictionary<string, List<string>> B = new Dictionary<string, List<string>>();
     // Key:Values are stored in dictionary B
     B.Add(..,..)

     Dictionary<string, List<string>> C = new Dictionary<string, List<string>>();
     foreach (var item in A)
     {
        if(B.ContainsValue(item.Value)) // This condition is not working, hence not going into the below block.
        {
           C.Add(item.Key, item.Value);
        }
     }

想要将字典 B 中存在的值添加到字典 C 中。

c# dictionary
1个回答
0
投票

ContainsValue 进行相等性检查。 List是引用类型,字典A和B中使用的列表不是同一个List。这里可以使用SequenceEqual来解决这个问题:

     Dictionary<string, List<string>> A = new Dictionary<string, List<string>>();
     // Key:Values are stored in dictionary A
     A.Add(..,..)
     Dictionary<string, List<string>> B = new Dictionary<string, List<string>>();
     // Key:Values are stored in dictionary B
     B.Add(..,..)

     Dictionary<string, List<string>> C = new Dictionary<string, List<string>>();
     foreach (var item in A)
     {
        if(B.Values.Any(x => item.Value.SequenceEqual(x)))
        {
           C.Add(item.Key, item.Value);
        }
     }

您可能会注意到的一个问题是,您在此处添加同一密钥的多个副本。这是一个单独的问题,可以通过使用不同的数据结构或添加唯一键来解决。

© www.soinside.com 2019 - 2024. All rights reserved.