[英]Check if case-insensitive string exist in List
I have an error with my List. 我的列表出错了。 Let me show you my idea: I have a loop, when finish loop 1, value will add to List, and it will continue when finish loop.
让我告诉你我的想法:我有一个循环,当完成循环1时,值将添加到List,并且它将在完成循环时继续。 Finally, i will a List that include all value in each loop.
最后,我将列出包含每个循环中所有值的List。
Then, i want to check if value is exist in List. 然后,我想检查列表中是否存在值。 If exist, i will do something.
如果存在,我会做点什么。
Example: 例:
Loop 1: List: A
循环1:列表:A
Loop 2: List: A,B
循环2:列表:A,B
Loop 3: List: A,B,A
循环3:列表:A,B,A
Because value A is Exist in List. 因为值A在列表中存在。 Then, i will do some thing if A exist in List
然后,如果A存在于List中,我将做一些事情
List<string> list = new List<string>();
foreach (DataRow r in dt.Rows)
{
string Url = r["Url"].ToString();
list.Add(Url);
if (list.Contains(Url, StringComparer.OrdinalIgnoreCase))
{
//dosomething
}
}
But nothing happen. 但什么都没发生。 Wish you help me improve my code.
希望你帮我改进我的代码。 Thanks !!!
谢谢 !!!
Try like this 试试这样吧
if(list.Where(o=> string.Equals(Url, o, StringComparison.OrdinalIgnoreCase)).Any())
{
// Exists in the list
}
Or 要么
if(list.FindIndex(o=> string.Equals(Url, o, StringComparison.OrdinalIgnoreCase))>-1){
// Exists in the list
}
Better approach would be using the List methods Exists
or Contains
, checkout the following program: 更好的方法是使用List方法
Exists
或Contains
,签出以下程序:
List<string> l = new List<string>();
l.Add("Madrid");
l.Add("Barcelona");
l.Add("NewYork");
l.Add("Chicago");
if(l.Exists(x=>string.Equals(x,"Chicago",StringComparison.OrdinalIgnoreCase))){
Console.WriteLine("Done !!");
}
In case of Exist, you can ignore the case using the StringComparison
enumeration, but that's not the case for Contains
, where you need to take care of the case, or else you need custom IComparer
to ignore the case 如果是Exist,你可以使用
StringComparison
枚举忽略这种情况,但对于Contains
不是这种情况,你需要处理这种情况,否则你需要自定义IComparer
来忽略这种情况
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.