Find if an integer exists in the list of integers

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 

It always seems to return false, even if the numbers match

any ideas?

+42
arrays c # integer
Oct 13 2018-10-13
source share
6 answers

If you need only true / false result

 bool isInList = intList.IndexOf(intVariable) != -1; 

if intVariable does not exist in the List, it will return -1

+65
Oct 13 2018-10-10
source share
β€” -

While your list is initialized with values ​​and this value really 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 there is indeed a true value.

+43
Oct 13 2018-10-10
source share

The way you did it is correct. It works great with this code: x is true. you may have made a mistake somewhere else.

 List<int> ints = new List<int>( new[] {1,5,7}); var i = 5; var x = ints.Contains(i); 
+3
Oct 13 2018-10-13
source share

Here is an extension method that allows you to code like an 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 things like this:

 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); 
+3
Oct 13 2018-10-10
source share
 bool vExist = false; int vSelectValue = 1; List<int> vList = new List<int>(); vList.Add(1); vList.Add(2); IEnumerable vRes = (from n in vListwhere n == vSelectValue); if (vRes.Count > 0) { vExist = true; } 
+1
Oct 13 2018-10-10
source share

You should refer to Selected not ids.Contains as the last line.

I just realized that this is a formatting issue, from OP. Regardless, you must reference the value in Selected. I recommend adding some calls to Console.WriteLine to see exactly what is printed on each line, as well as what each value is.

After your update: ids is an empty list, how is it not throwing a NullReferenceException? Since it was never initialized in this code block

0
Oct 13 2018-10-13
source share



All Articles