Check if a string exists in the list

I have a bug with my list. Let me show you my idea: I have a loop, when loop 1 ends, the value will add to the List, and it will continue when the loop ends. Finally, I will be a List that includes all the values ​​in each loop.

Then, I want to check if the value exists in the List. If there is, I'll do something.

Example:

Loop 1: List: A

Loop 2: List: A, B

Loop 3: List: A, B, A

Because the value A exists in the list. Then I will do something if A exists 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 happens. I wish you help me improve my code. Thank!!!

+3


source to share


2 answers


try it

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
}

      

+6


source


Better approach would be to use List methods Exists

or Contains

, check out 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 the case of Exist, you can ignore the case using an enum StringComparison

, but that is not Contains

where you need to take care of this case, otherwise you need a custom IComparer

one to ignore the case

+3


source







All Articles