DYNSTy
DYNSTy

Reputation: 257

How to check if an Integer exists in a list?

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

Upvotes: 12

Views: 44795

Answers (5)

user3181923
user3181923

Reputation: 1

Checking if a List<int>, with the method Contains, contains an integer is a O(n) operation. It means it takes linearly longer to execute the longer the list is. Checking if an int is already present in a HashSet<int> is an O(1) operation. Any class called Set in any programming language only contains a unique value (by definition from math).

If the list only contains a small number of integers in a small range, say for example 100 to 1000, it is more efficient to assign or calculate the min and max of those numbers. Then with an with if statement you check if it is in the range. Then for the small range of integers you make a bool array (bool[]) as large as the range and initialize the positions of that array with true for the int's that are "in" the set.

Make sure you have a situation where you can do the min/max and the bool array initialization before running the "check if an int is in the list" operation.

I optimized a method like this today, it got 24 000 times faster.

Upvotes: 0

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98868

You can use List.Contains() method.

Determines whether an element is in the List<T>.

Like;

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);
}

Output will be;

1
2
3
4
5
6

Here a demonstration.

Upvotes: 4

Satpal
Satpal

Reputation: 133453

You can use List.Contains Method

myList.Contains(x)

OR

myList.Any(p => p == x)    

Upvotes: 25

Davecz
Davecz

Reputation: 1221

List have a Contains method

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

Upvotes: 1

ProgramFOX
ProgramFOX

Reputation: 6390

Try to use the Contains method:

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

Upvotes: 1

Related Questions