繁体   English   中英

不区分大小写的字典无法按预期工作

[英]Case-Insensitive dictionary not working as expected

我正在从 OsiSoft “PI”系统的字典中缓存一些数据,并通过字符串键对其进行索引。 键来自不同系统中的用户输入,并且大小写混合。 OsiSoft 系统键不区分大小写,所以我的字典也需要不区分大小写。 但是,字典没有按预期工作。

字典定义如下:

Dictionary<string, PIPoint> PointsDictionary = new Dictionary<string, PIPoint>(StringComparer.CurrentCultureIgnoreCase);

它是从派生自 IList 的 OsiSoft 结构返回的结构中填充的

PointsDictionary = RegisteredPoints.ToDictionary(x => x.Name, x => x);

当我尝试从字典中返回 PIPoint 值时,它没有按预期工作。 我想以小写、大写或混合大小写传递密钥,并获得相同的值。

    public PIPoint GetPoint(string tag)
    {
        //sfiy-1401a/c6
        //SFIY-1401A/C6
        Debug.WriteLine("sfiy-1401a/c6" + ": " + PointsDictionary.ContainsKey("sfiy-1401a/c6"));
        Debug.WriteLine("SFIY-1401A/C6" + ": " + PointsDictionary.ContainsKey("SFIY-1401A/C6"));
        Debug.WriteLine("Match?" + ": " + "SFIY-1401A/C6".Equals("sfiy-1401a/c6", StringComparison.CurrentCultureIgnoreCase));
        if (tag == null || !PointsDictionary.ContainsKey(tag)) return null;
        return PointsDictionary[tag];
    }

运行上述程序时来自调试器的 Output:

sfiy-1401a/c6:错误

SFIY-1401A/C6:真

匹配?:是的

我是否从根本上误解了不区分大小写的字典的工作方式,或者我填充它的方式有什么(转换 IList.ToDictionary()),这意味着它没有按预期工作?

该字典被定义为不区分大小写,但随后您将用区分大小写的字典覆盖它。

// definition 
Dictionary<string, PIPoint> PointsDictionary = new Dictionary<string, PIPoint>(StringComparer.CurrentCultureIgnoreCase);

// later *reassignment*
PointsDictionary = RegisteredPoints.ToDictionary(x => x.Name, x => x);

你看,你正在替换这个值,当你覆盖这个值时,原来的比较器就丢失了 调用ToDictionary时需要再次指定比较器。 幸运的是,有一个重载需要一个关键比较器:

PointsDictionary = RegisteredPoints.ToDictionary(x => x.Name, x => x, StringComparer.CurrentCultureIgnoreCase);

请注意, ToDictionary也有采用键选择器(和比较器)的重载,因此您可以简化为:

PointsDictionary = RegisteredPoints.ToDictionary(x => x.Name, StringComparer.CurrentCultureIgnoreCase);

您甚至可以传递Comparer的比较器,这样您就不必确切地记住它是什么类型:

PointsDictionary = RegisteredPoints.ToDictionary(x => x.Name, PointsDictionary.Comparer);

或者,您可以清除字典并重新添加所有项目,这将保留原始比较器:

PointsDictionary.Clear():
foreach(var p in RegisteredPoints) 
   PointsDictionary[p.Name] = p:

暂无
暂无

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

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