简体   繁体   English

在区分大小写的字典 C# 上进行不区分大小写的搜索

[英]Case insensitive search on Case sensitive dictionary C#

I have a case Sensitive dictionary,我有一个区分大小写的字典,

 Dictionary<string, uint> itemNames = new Dictionary<string, uint>(StringComparer.Ordinal);

So I can have case sensitive keys in this dictionary.所以我可以在这本字典中有区分大小写的键。

For example I can have below key value pairs,例如我可以有以下键值对,

  1. { test, 10 } {测试,10}
  2. { TEST, 20 } {测试,20}
  3. { test1, 30 } { 测试 1, 30 }
  4. { test2, 40 } { 测试 2, 40 }

... ...

When someone passes key, I want to retrieve the value.当有人传递密钥时,我想检索该值。 The retrieval should be partially case insensitive which means, If exact case is matched then return the case sensitive result, if case sensitive key doesn't exists then retrieve case insensitive key value.检索应该部分不区分大小写,这意味着,如果完全匹配,则返回区分大小写的结果,如果不存在区分大小写的键,则检索不区分大小写的键值。

For example, with the above values inserted in the dictionary例如,将上述值插入到字典中

If user passes key as "TEST" I need to return 20.如果用户将密钥作为“TEST”传递,我需要返回 20。

If user passes key as "TEST1" , the case sensitive key is not found so I need to return 30.如果用户将密钥作为 "TEST1" 传递,则找不到区分大小写的密钥,因此我需要返回 30。

How to achieve this in C# ?如何在 C# 中实现这一点?

You should first use TryGetValue to check if there is an item.您应该首先使用TryGetValue来检查是否有项目。 If not, select the first match:如果没有,请选择第一个匹配项:

string key = "test1";
int val;
if (!itemNames.TryGetValue(key, out val))
{
    val = itemNames.FirstOrDefault
                    (k => string.Equals(k.Key, key, StringComparison.OrdinalIgnoreCase)
                    )?.Value ?? 0;
}

Be aware for the performance of this code though.但是请注意此代码的性能。 If you have a large dictionary with a lot of misses on the first attempt, a second (case-insensitive) dictionary would be better.如果您有一本大字典,但在第一次尝试时有很多遗漏,那么第二个(不区分大小写)字典会更好。

Performance wise, the only way to get O(1) average lookup time is to have two dictionaries, where one will use a default comparer, and the other one a case-insensitive one:性能方面,获得O(1)平均查找时间的唯一方法是拥有两个字典,其中一个将使用默认比较器,另一个使用不区分大小写的:

// map each string to single item
Dictionary<string, int> CaseSensitive;
    
// map each string to multiple items, case insensitive
Dictionary<string, List<KeyValuePair<string, int>>> CaseInsensitive;

or even甚至

// map each string to single item
Dictionary<string, int> CaseSensitive;
    
// map each string to multiple items, case insensitive, with O(1) lookup time
Dictionary<string, HashSet<KeyValuePair<string, int>>> CaseInsensitive;

Your case insensitive search can then properly return all matches, not just the most recently inserted one.然后,您的不区分大小写的搜索可以正确返回所有匹配项,而不仅仅是最近插入的匹配项。

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

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