Mr.*_*Boy 135 c# collections generic-collections
如果我有一个Dictionary<String,...>是否有可能使方法ContainsKey不区分大小写?
这似乎是相关的,但我没有理解它:c#Dictionary:通过声明使Key不区分大小写
Kon*_*lph 280
这似乎是相关的,但我没有理解它:c#Dictionary:通过声明使Key不区分大小写
这确实是相关的.解决方案是告诉字典实例不要使用标准字符串比较方法(区分大小写),而是使用不区分大小写的方法.这是使用适当的构造函数完成的:
var dict = new Dictionary<string, YourClass>(
StringComparer.InvariantCultureIgnoreCase);
Run Code Online (Sandbox Code Playgroud)
构造函数需要一个IEqualityComparer告诉字典如何比较键的字符串.
StringComparer.InvariantCultureIgnoreCase为您提供一个IEqualityComparer以不区分大小写的方式比较字符串的实例.
Ste*_*eve 20
var myDic = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
myDic.Add("HeLlo", "hi");
if (myDic.ContainsKey("hello"))
Console.WriteLine(myDic["hello"]);
Run Code Online (Sandbox Code Playgroud)
A.G*_*.G. 11
如果您无法控制实例创建,假设您的对象已从 json 等中消除,您可以创建一个从字典类继承的包装类。
public class CaseInSensitiveDictionary<TValue> : Dictionary<string, TValue>
{
public CaseInSensitiveDictionary() : base(StringComparer.OrdinalIgnoreCase){}
}
Run Code Online (Sandbox Code Playgroud)
Kur*_*ula 10
您从第三方或外部dll提取字典的机会很少.使用linq
YourDictionary.Any(i => i.KeyName.ToLower().Contains("yourstring")))
我刚刚遇到了同样的麻烦,我需要在 ASP.NET Core 控制器中使用不区分大小写的字典。
我写了一个扩展方法来解决这个问题。也许这对其他人也有帮助......
public static IDictionary<string, TValue> ConvertToCaseInSensitive<TValue>(this IDictionary<string, TValue> dictionary)
{
var resultDictionary = new Dictionary<string, TValue>(StringComparer.InvariantCultureIgnoreCase);
foreach (var (key, value) in dictionary)
{
resultDictionary.Add(key, value);
}
dictionary = resultDictionary;
return dictionary;
}
Run Code Online (Sandbox Code Playgroud)
使用扩展方法:
myDictionary.ConvertToCaseInSensitive();
Run Code Online (Sandbox Code Playgroud)
然后从字典中获取一个值:
myDictionary.ContainsKey("TheKeyWhichIsNotCaseSensitiveAnymore!");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49585 次 |
| 最近记录: |