C#包含元组上的密钥

时间:2012-04-25 17:04:45

标签: c# class dictionary

我有一个字典,它接受一个元组函数和一个int

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

将Tuple类定义为

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">))

但是我收到了一个重载错误。有什么建议吗?

5 个答案:

答案 0 :(得分:6)

您提供的代码无效,因为您试图在实际对象所在的位置提供类型定义(并且类型定义也是无效的,因为字符串实际上不是类型{{1通用期望)。如果元组是字典的键值,那么你可以这样做:

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)) Equals以正确识别内存中的两个单独内容实例是一样的。

答案 1 :(得分:4)

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

答案 2 :(得分:3)

要将您的Tuple用作词典中的键&lt;&gt;您需要正确实施方法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")

的效果

有关哈希码生成的更多信息: What is the best algorithm for an overridden System.Object.GetHashCode?

答案 3 :(得分:1)

.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

答案 4 :(得分:0)

Tuple<type,type> tuple = new Tuple("firsdtname", "lastname")

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

相关问题