我有一个像这样的单词列表:
List<string> list = new List<string>();
list.Add("Horse");
list.Add("Shorse"):
我想在列表中搜索特定的字符串,无论如何,但如果我这样做,它必须是一个精确的匹配
if (list.Contains("horse",StringComparer.CurrentCultureIgnoreCase))
{
//do something
}
它会找到Horse和Shorse。
如何实现我自己的自定义Contains方法,以找到完全匹配?
答案 0 :(得分:2)
您已在列表中正确查找完全匹配项。您明确指定的唯一事情是您要忽略匹配的情况。因此,如果列表中有Horse
,您还可以将其设为horse
或hOrsE
。但你找不到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
答案 1 :(得分:0)
您可以将两个字符串都设置为小写(或大写字母,无论哪个漂浮在您的船上)并进行比较。您可以使用Any
代替Contains
List<string> list = new List<string>();
list.Add("Horse");
list.Add("Shorse");
var needle = "horse";
var contains = list.Any(x => x.ToLower() == needle.ToLower()); // true
答案 2 :(得分:0)
要查找匹配忽略大小写,您可以执行以下操作:
var valueToMatch = "horse";
var matchedValue = list.FirstOrDefault(x => x.Equals(valueToMatch, StringComparison.OrdinalIgnoreCase);
Debug.WriteLine(matchedValue);
答案 3 :(得分:-1)
修改强>
这不是答案,因为我从另一个方面得到了问题。这解决了区分大小写的情况。因此,如果你将所有案例都降低,那么检查它是否应该有效。
<强> TESTED!强>
加载您的数据并使用此功能查找列表中确切字符序列的索引,并且区分大小写!
//populate your main list
List<string> YourList = new List<string>();
YourList.Add("Horse");
YourList.Add("Shorse");
YourList.Add("HorseS");
//find index of matching sequence of characters
// this return 0
int index = YourList.FindIndex(collection => collection.SequenceEqual("Horse"));
Console.WriteLine(index);
// this return 1
index = YourList.FindIndex(collection => collection.SequenceEqual("Shorse"));
Console.WriteLine(index);
// this return -1 (not found)
index = YourList.FindIndex(collection => collection.SequenceEqual("SHorse"));
Console.WriteLine(index);
// this return -1 (not found)
index = YourList.FindIndex(collection => collection.SequenceEqual("horse"));
Console.WriteLine(index);
// this return 2
index = YourList.FindIndex(collection => collection.SequenceEqual("HorseS"));
Console.WriteLine(index);
这是输出: