具有元组键的不区分大小写的字典 [英] Case Insensitive Dictionary with Tuple Key

查看:92
本文介绍了具有元组键的不区分大小写的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,其中的键是一个元组,其中第一项是日期,第二项是字符串。我希望字典不区分大小写。

I have a dictionary where the key is a Tuple where the first item is a Date and the second item is a string. I would like the dictionary to be case insensitive.

我知道,如果键只是一个字符串,我可以在声明字典时将StringComparer.OrdinalIgnoreCase用作参数,但是

I know that if the key was just a string I could pass StringComparer.OrdinalIgnoreCase as a parameter when declaring the dictionary, but this does not seem to work when the key is a Tuple.

是否有某种方法可以指定StringComparer用于元组的第二个项目?

Is there some way to specify the StringComparer to use on the second item of the Tuple?

谢谢

推荐答案

使用 Dictionary 构造函数的此重载,它允许您指定自定义键的比较器。您将伴随创建一个实现

Use this overload of the Dictionary constructor, which allows you to specify a custom comparer for the keys. You would accompany this with creating a class that implements

IEqualityComparer<Tuple<string, DateTime>>

看起来像这样:

class CustomEqualityComparer : IEqualityComparer<Tuple<string, DateTime>>
{

    public bool Equals(Tuple<string, DateTime> lhs, Tuple<string, DateTime> rhs)
    {
        return
          StringComparer.CurrentCultureIgnoreCase.Equals(lhs.Item1, rhs.Item1)
       && lhs.Item2 == rhs.Item2;
    }


    public int GetHashCode(Tuple<string, DateTime> tuple)
    {
        return StringComparer.CurrentCultureIgnoreCase.GetHashCode(tuple.Item1)
             ^ tuple.Item2.GetHashCode();
    }
}

这里没有参数检查,所以请不要将此视为生产代码。另外,还需要注意使 Equals GetHashCode 实现满足的所有重要条件。如果两个元组比较相等,则它们必须具有相同的哈希码。在处理自定义文本比较时,如果不加注意的话,很容易引入错误:例如,使用 ToLowerInvariant 代替 ToLower 以上将是一个错误(尽管可能会出现一段时间)。

There are no argument checks here, so please don't treat this as production code. Also, care needs to be taken so that the Equals and GetHashCode implementations satisfy the all-important condition that if two tuples compare equal, they must have the same hash code. When dealing with custom text comparisons it is easy to introduce bugs if not extra careful: for example, using ToLowerInvariant instead of ToLower above would be a bug (albeit one that might not surface for some time).

这篇关于具有元组键的不区分大小写的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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