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. Finally, i will a List that include all value in each loop.
Then, i want to check if value is exist in List. If exist, i will do something.
Example:
Loop 1: List: A
Loop 2: List: A,B
Loop 3: List: A,B,A
Because value A is Exist in List. Then, i will do some thing if A exist in 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<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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With