C#-元组或字典的其他多键变体,但具有置换性 [英] C# - Tuple or other multikey variant for Dictionary, but with permutability

查看:104
本文介绍了C#-元组或字典的其他多键变体,但具有置换性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为下面的问题scratch之以鼻. 我想创建一个使用多个键的字典.我提出了建议使用元组作为选择方法的解决方案.我认为这是一个不错的选择.但是我的问题有以下特点.我想使键可置换"(对不起,如果我在这里使用错误的the语).我的意思是以下内容.我希望dict[<key1,key2>的结果与dict[<key2,<key1>]相同,因为我要存储的数据对于键的顺序是不变的.

I am scratching my head over the following problem. I want to create a dictionary, which uses multiple keys. I came along the solutions suggesting tuples as the method of choice. I think this i a good way to go. However my problem has the following speciality. I would like to make the keys "permutable" (Sorry, if I am using the wrong slang here). What I mean with this, is the following. I want the result of dict[<key1,key2> to be the same as with dict[<key2,<key1>], because the data that I want to store is invariant to the order of keys.

作为示例,请参见下面的代码,该代码当前当然不能产生我期望的结果.我希望置换键的结果与键元组的结果相同.

As an example see the following code, which of course does at the moment not yield the result I am hoping for. I want the result with permuted key to be the same as for the key-tuple.

    Tuple<string, string> key = new Tuple<string, string>("Name1", "Name2");
    Dictionary<Tuple<string,string>, double> dict = new Dictionary<Tuple<string, string>, double>();
    dict.Add(key, 5.0);

    Console.WriteLine(dict[key]);

    Tuple<string, string> permutedKey = new Tuple<string, string>("Name2", "Name1");
    Console.WriteLine(dict[permutedKey]);

所有这些的原因,我必须存储数据,该数据必须使用两个键进行索引,但本质上始终是对称的.因此无需将其存储两次.

The reason for all this, I have to store data, which has to be indexed with two keys, but is essentially always symetrical. So there is no need, to store it two times.

推荐答案

您可以定义自己的自定义相等比较器并在字典中使用它:

You can define your own custom equality comparer and use it in the dictionary:

class TupleComparer<T> : IEqualityComparer<Tuple<T, T>>
{
    public bool Equals(Tuple<T, T> x, Tuple<T, T> y)
    {
        return object.Equals(x.Item1, y.Item1) && object.Equals(x.Item2, y.Item2) ||
               object.Equals(x.Item1, y.Item2) && object.Equals(x.Item2, y.Item1);
    }

    public int GetHashCode(Tuple<T, T> obj)
    {
        return obj.Item1.GetHashCode() + obj.Item2.GetHashCode();
    }
}

然后,您可以创建将比较器实例传递给它的字典:

Then, you can create the dictionary passing it an instance of the comparer:

Tuple<string, string> key = new Tuple<string, string>("Name1", "Name2");

Dictionary<Tuple<string,string>, double> dict = 
    new Dictionary<Tuple<string, string>, double>(new TupleComparer<string>());

dict.Add(key, 5.0);
Console.WriteLine(dict[key]);

var permutedKey = new Tuple<string, string>("Name2", "Name1");
Console.WriteLine(dict[permutedKey]);

这篇关于C#-元组或字典的其他多键变体,但具有置换性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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