Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 不区分大小写的字典未按预期工作_C#_Dictionary - Fatal编程技术网

C# 不区分大小写的字典未按预期工作

C# 不区分大小写的字典未按预期工作,c#,dictionary,C#,Dictionary,我正在OsiSoft PI系统的字典中缓存一些数据,并通过字符串键对其进行索引。这些键来自不同系统中的用户输入,并且混合了大小写。OsiSoft系统键不区分大小写,因此我需要字典也不区分大小写。然而,字典并没有像预期的那样工作 该词典的定义如下: Dictionary<string, PIPoint> PointsDictionary = new Dictionary<string, PIPoint>(StringComparer.CurrentCultureIgnore

我正在OsiSoft PI系统的字典中缓存一些数据,并通过字符串键对其进行索引。这些键来自不同系统中的用户输入,并且混合了大小写。OsiSoft系统键不区分大小写,因此我需要字典也不区分大小写。然而,字典并没有像预期的那样工作

该词典的定义如下:

Dictionary<string, PIPoint> PointsDictionary = new Dictionary<string, PIPoint>(StringComparer.CurrentCultureIgnoreCase);
当我试图从字典中返回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];
    }
运行上述程序时调试器的输出:

sfiy-1401a/c6:错误

SFIY-1401A/C6:正确

匹配?:对

我是否从根本上误解了不区分大小写的字典的工作原理,或者我填充它的方式中是否存在某种东西(将IList.ToDictionary转换为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, StringComparer.CurrentCultureIgnoreCase);
您甚至可以通过考试,这样您就不必准确地记住它是什么类型的:

PointsDictionary = RegisteredPoints.ToDictionary(x => x.Name, PointsDictionary.Comparer);
或者,您可以清除字典并将所有项重新添加到字典中,以保留原始比较器:

PointsDictionary = RegisteredPoints.ToDictionary(x => x.Name, x => x, StringComparer.CurrentCultureIgnoreCase);
PointsDictionary.Clear():
foreach(var p in RegisteredPoints) 
   PointsDictionary[p.Name] = p:

不,你基本上误解了任务的工作原理。您将字典重新分配给一个新的区分大小写的字典,而不是添加到您创建的字典中。是的,这不是字典的问题,而是引用类型和变量分配的D'Oh时刻!
PointsDictionary.Clear():
foreach(var p in RegisteredPoints) 
   PointsDictionary[p.Name] = p: