Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find if an integer exists in a list of integers

Tags:

arrays

c#

integer

i have this code:

  List<T> apps = getApps();          List<int> ids;          List<SelectListItem> dropdown = apps.ConvertAll(c => new SelectListItem         {             Selected = ids.Contains(c.Id),             Text = c.Name,             Value = c.Id.ToString()         }).ToList();   ids.Contains 

seems to always return false even though the numbers do match

any ideas?

like image 574
leora Avatar asked Oct 13 '10 13:10

leora


People also ask

How do you check if an integer is present in a list?

You can use List. Contains() method. Determines whether an element is in the List<T> .

How do you see if an integer is in a list Python?

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

Can a list contains an integer as an element?

As you would expect, we can also assign list values to variables and pass lists as parameters to functions. A list can contain only integer items.


2 Answers

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

like image 136
Bobby Borszich Avatar answered Sep 20 '22 08:09

Bobby Borszich


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.

like image 25
Rune Grimstad Avatar answered Sep 22 '22 08:09

Rune Grimstad