find if an integer exists in a list of integers
The way you did is correct. It works fine with that code: x is true. probably you made a mistake somewhere else.
List<int> ints = new List<int>( new[] {1,5,7}); // 1
List<int> intlist=new List<int>() { 0,2,3,4,1}; // 2
var i = 5;
var x = ints.Contains(i); // return true or false
Here is a extension method, this allows coding like the SQL IN command.
public static bool In<T>(this T o, params T[] values)
{
if (values == null) return false;
return values.Contains(o);
}
public static bool In<T>(this T o, IEnumerable<T> values)
{
if (values == null) return false;
return values.Contains(o);
}
This allows stuff like that:
List<int> ints = new List<int>( new[] {1,5,7});
int i = 5;
bool isIn = i.In(ints);
Or:
int i = 5;
bool isIn = i.In(1,2,3,4,5);
As long as your list is initialized with values and that value actually exists in the list, then Contains should return true.
I tried the following:
var list = new List<int> {1,2,3,4,5};
var intVar = 4;
var exists = list.Contains(intVar);
And exists is indeed set to true.
If you just need a true/false result
bool isInList = intList.IndexOf(intVariable) != -1;
if the intVariable does not exist in the List it will return -1