繁体   English   中英

元组上的C#containskey

[英]C# containskey on tuple

我有一个带元组函数和int的字典

Dictionary<Tuple<string,string>, int> fullNames = new Dictionary<Tuple<string,string>, int>();

元组类定义为

public class Tuple<T, T2> 
{ 
    public Tuple(T first, T2 second) 
    { 
        First = first; 
        Second = second; 
    } 
    public T First { get; set; } 
    public T2 Second { get; set; } 

}

我想这样使用Containskey函数

if (fullNames.ContainsKey(Tuple<"firstname","lastname">))

但是我遇到了过载错误。 有什么建议么?

您提供的代码无效,因为您试图在实际对象应该放置的地方提供类型定义(并且类型定义也无效,因为字符串实际上不是泛型的System.String类型。期望)。 如果元组是字典的键值,则可以执行以下操作:

if(fullNames.ContainsKey(new Tuple<string, string>("firstname", "lastname")))

但是,由于内存中创建的具有相同属性的两个元组不一定是同一对象,因此您可能会遇到引用相等问题。 这样做会更好:

Tuple<string, string> testTuple = new Tuple<string, string>("firstname", "lastname");
if(fullNames.Keys.Any(x => x.First == testTuple.First && x.Second == testTuple.Second))

这将告诉您是否存在共享相同属性数据的密钥。 然后访问该元素将变得同样复杂。

编辑:长话短说,如果您打算对键使用引用类型,则需要确保您的对象以适当的方式实现EqualsGetHashCode ,以正确地识别内存实例中的两个相同。

if (fullNames.ContainsKey(new Tuple<string, string> ("firstname", "lastname")))
{ /* do stuff */ }

为了将您的Tuple用作Dictionary <>中的键,您需要正确地实现GetHashCodeEquals方法:

public class Tuple<T, T2> 
{ 
    public Tuple(T first, T2 second) 
    { 
        First = first; 
        Second = second; 
    } 
    public T First { get; set; } 
    public T2 Second { get; set; }

    public override int GetHashCode()
    {
      return First.GetHashCode() ^ Second.GetHashCode();
    }

    public override Equals(object other)
    {
       Tuple<T, T2> t = other as Tuple<T, T2>;
       return t != null && t.First.Equals(First) && t.Second.Equals(Second);
    }

}

否则,将通过引用进行密钥相等性检查。 结果是new Tuple("A", "B") != new Tuple("A", "B")

有关哈希码生成的更多信息: 重写的System.Object.GetHashCode的最佳算法是什么?

.Net 4.0具有Tuple类型,该类型适用于您的情况,因为Equal方法已重载以使用您类型中的Equal

Dictionary<Tuple<string, string>, int> fullNames = 
    new Dictionary<Tuple<string, string>, int>();
fullNames.Add(new Tuple<string, string>("firstname", "lastname"), 1);
Console.WriteLine(fullNames.ContainsKey(
    new Tuple<string, string>("firstname","lastname"))); //True
Tuple<type,type> tuple = new Tuple("firsdtname", "lastname")

您已经编写了代码来创建未知类型的atuple的实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM