如何从两个字典中搜索一个值并将其添加到另一个字典中

问题描述 投票: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);
   }
}
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.