C# Dictionary<string,string> TryGetValue不要区分大小写,不区分大小写的字典
在使用 Dictionary<string, string>
时,默认情况下键的比较是区分大小写的。如果你希望键的比较不区分大小写,可以在创建字典时指定一个自定义的比较器。例如,使用 StringComparer.OrdinalIgnoreCase
来忽略大小写。下面是一个示例:
C# 全选
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// 创建不区分大小写的字典
var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
// 添加键值对
dictionary.Add("Key1", "Value1");
dictionary.Add("Key2", "Value2");
// 尝试获取值
if (dictionary.TryGetValue("KEY1", out string value))
{
Console.WriteLine($"Found: {value}"); // 输出: Found: Value1
}
else
{
Console.WriteLine("Key not found");
}
if (dictionary.TryGetValue("key2", out value))
{
Console.WriteLine($"Found: {value}"); // 输出: Found: Value2
}
else
{
Console.WriteLine("Key not found");
}
}
}
在这个示例中,我们创建了一个不区分大小写的字典。无论是用 "Key1"
还是 "KEY1"
或者 "key1"
来查找键,都会成功并返回正确的值。
使用自定义比较器
如果你有更复杂的需求,还可以实现自己的比较器,只需要实现 IEqualityComparer<string>
接口。以下是一个简单的示例:
C# 全选
using System;
using System.Collections.Generic;
public class CaseInsensitiveComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return string.Equals(x, y, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(string obj)
{
return obj.ToLowerInvariant().GetHashCode();
}
}
public class Program
{
public static void Main()
{
var dictionary = new Dictionary<string, string>(new CaseInsensitiveComparer());
dictionary.Add("Key1", "Value1");
dictionary.Add("Key2", "Value2");
if (dictionary.TryGetValue("KEY1", out string value))
{
Console.WriteLine($"Found: {value}");
}
else
{
Console.WriteLine("Key not found");
}
if (dictionary.TryGetValue("key2", out value))
{
Console.WriteLine($"Found: {value}");
}
else
{
Console.WriteLine("Key not found");
}
}
}
这个示例创建了一个自定义的比较器 CaseInsensitiveComparer
,并使用它来初始化字典。无论键的大小写如何,查找操作都不会区分大小写。
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 张国生