不区分大小写的搜索列表 [英] Case-Insensitive List Search
问题描述
我有一个列表 testList
包含一串字符串。我想一个新的字符串添加到 testList
只有当它没有在列表中已经存在。因此,我需要做一个区分大小写的搜索列表中,并使其有效。我不能使用包含
,因为没有考虑到外壳。我也不想用 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");
这工作,但它也匹配部分单词。如果列表中包含山羊,我不能,因为它声称,燕麦已经在列表中添加燕麦。有没有办法在不区分大小写的方式,字都完全匹配高效地搜索列表?谢谢
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屋!