Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

c# - Searching a List<string> for an EXACT case insenitive match

I have a list of words like so :

List<string> list = new List<string>();
list.Add("Horse");
list.Add("Shorse"):

I want to search the list for a specific string, regardless of case, but it has to be an EXACT match, if i do

if (list.Contains("horse",StringComparer.CurrentCultureIgnoreCase)) 
{ 
    //do something
}

It will find both Horse and Shorse.

How can i implement my own custom Contains method that will find an exact match?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are already correctly looking for exact matches in your list. The only thing which you explicitly specified is that you want to ignore the case of the matches. So if you have a Horse in the list, you can also find it as horse, or hOrsE. But you cannot find it as orse:

List<string> list = new List<string>();
list.Add("Horse");
list.Add("Shorse");

// we can find it with different casing
Console.WriteLine(list.Contains("horse", StringComparer.CurrentCultureIgnoreCase)); // true
Console.WriteLine(list.Contains("shorse", StringComparer.CurrentCultureIgnoreCase)); // true

// but not elements that are not in the list
Console.WriteLine(list.Contains("orse", StringComparer.CurrentCultureIgnoreCase)); // false

// if we don’t want to ignore the case, we can also do that
Console.WriteLine(list.Contains("Horse")); // true
Console.WriteLine(list.Contains("Shorse")); // true
Console.WriteLine(list.Contains("horse")); // false
Console.WriteLine(list.Contains("shorse")); // false

// and let’s look at a list with only Shorse to be sure…
list.Clear();
list.Add("Shorse");
Console.WriteLine(list.Contains("horse")); // false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...