不区分大小写的列表搜索 [英] Case-Insensitive List Search
问题描述
我有一个包含一堆字符串的列表 testList
.我想在 testList
中添加一个新字符串,如果它不存在于列表中.因此,我需要对列表进行不区分大小写的搜索并使其高效.我不能使用 Contains
因为这没有考虑到大小写.出于性能原因,我也不想使用 ToUpper/ToLower
.我遇到了这个方法,它有效:
I have a list testList
that contains a bunch of strings. I would like to add a new string into the testList
only if it doesn't already exist in the list. Therefore, I need to do a case-insensitive search of the list and make it efficient. I can't use Contains
because that doesn't take into account the casing. I also don't want to use ToUpper/ToLower
for performance reasons. I came across this method, which works:
if(testList.FindAll(x => x.IndexOf(keyword,
StringComparison.OrdinalIgnoreCase) >= 0).Count > 0)
Console.WriteLine("Found in list");
这有效,但它也匹配部分单词.如果列表包含goat",我不能添加oat",因为它声称oat"已经在列表中.有没有办法以不区分大小写的方式有效地搜索列表,其中单词必须完全匹配?谢谢
This works, but it also matches partial words. If the list contains "goat", I can't add "oat" because it claims that "oat" is already in the list. Is there a way to efficiently search lists in a case insensitive manner, where words have to match exactly? thanks
推荐答案
代替 String.IndexOf,使用 String.Equals 以确保您没有部分匹配.也不要使用 FindAll,因为它会遍历每个元素,请使用 FindIndex(它在它击中的第一个处停止).
Instead of String.IndexOf, use String.Equals to ensure you don't have partial matches. Also don't use FindAll as that goes through every element, use FindIndex (it stops on the first one it hits).
if(testList.FindIndex(x => x.Equals(keyword,
StringComparison.OrdinalIgnoreCase) ) != -1)
Console.WriteLine("Found in list");
交替使用一些 LINQ 方法(也会在它遇到的第一个方法上停止)
Alternately use some LINQ methods (which also stops on the first one it hits)
if( testList.Any( s => s.Equals(keyword, StringComparison.OrdinalIgnoreCase) ) )
Console.WriteLine("found in list");
这篇关于不区分大小写的列表搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!