C#检查字典是否包含作为引用类型的键 [英] C# Check if dictionary contains key which is a reference type

查看:63
本文介绍了C#检查字典是否包含作为引用类型的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 Dictionary< int [],int> ,其中包含2个条目

If I have a Dictionary<int[], int>, which contains 2 entries

{1, 2, 3} , 1 and
{4, 5, 6} , 2

如何检查字典是否包含键 {1、2、3} ?如果我这样做:

How do I check whether the dictionary contains the key {1, 2, 3}? If i do:

if (dictionary.ContainsKey(new int[] {1,2,3})
{
  // do things
}

由于创建的数组与键数组不同,因此不会返回正确的结果.我知道您可以为自定义类重写Equals方法,但是还有另一种方法来检查以数组为键的字典是否包含一个键数组与比较数组具有相同值的条目吗?

It will not return the correct result as the created array is different from the key array. I know you can override the Equals method for a custom class, but is there another way to check if a dictionary which has an array as the key, contains an entry whose key array has the same values within it as the comparison array?

推荐答案

好吧,通过引用比较数组,所以我们有

int[] a = new int[] {1, 2, 3};

int[] b = new int[] {1, 2, 3}; // same content, different reference

// Prints "No"
Console.WriteLine(a.Equals(b) ? "Yes" : "No");

Dictionary<int[], string> dict = new Dictionary<int[], string>() {{
  a, "Some Value"}};

// Prints "Not Found"
Console.WriteLine(dict.TryGetValue(b, out var value) ? value : "Not Found");

因此,我们必须解释.Net如何比较数组;我们可以使用比较器:

So we have to explain .Net how to compare arrays; we can do it with a comparer:

public class SequenceEqualityComparer<T> : IEqualityComparer<IEnumerable<T>> {
  public bool Equals(IEnumerable<T> x, IEnumerable<T> y) {
    if (ReferenceEquals(x, y))
      return true;
    else if (null == x || null == y)
      return false;

    return Enumerable.SequenceEqual(x, y, EqualityComparer<T>.Default); 
  }

  public int GetHashCode(IEnumerable<T> obj) =>
    obj == null ? 0 : obj.FirstOrDefault()?.GetHashCode() ?? 0;
}

我们应该在提及比较器时声明字典:

And we should declare the dictionary while mentioning the comparer:

Dictionary<int[], string> dict = 
  new Dictionary<int[], string>(new SequenceEqualityComparer<int>()) {
    {a, "Some Value"}};

现在我们可以照常营业:

Now we can do business as usual:

// Returns "Some Value" 
Console.WriteLine(dict[b]);

这篇关于C#检查字典是否包含作为引用类型的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆