How to check if an integer exists in a list?

I am using an Integer list. Before adding the "x" element, I need to check if the "x" exists in the list. how can this be implemented

+4
source share
4 answers

You can use the List.Contains Method

myList.Contains(x)

OR

myList.Any(p => p == x)    
+11
source

The list contains the Contains method.

List<Int32> list = new List<int>();
if (list.Contains(val))
{
   //...
}
+1
source

You can use the method List.Contains().

Determines if an item is in List<T>.

how

List<int> list = new List<int>(){1, 2, 3, 4, 5};
if(!list.Contains(6))
    list.Add(6);
foreach (var i in list)
{
   Console.WriteLine(i);
}

The output will be:

1
2
3
4
5
6

Here . demonstration

+1
source

Try using the methodContains :

if (yourList.Contains(x))
{
    // this code gets executed if the list contains 'x'
}
0
source

All Articles