Checking if List <T> contains the given integer

I use the List<T> array to store the entire ID that I read from my database file.

do allows me to say that I have ID: 5, 8, 15

What I'm trying to do is check if the user input matches one of the elements of this array.

How to do it?

I tried using Contains or Find, but I can't get it to work.

A bit of code that doesn't seem to work. It shows only Entry ID doesn't exist! only if I enter the letter (?).

  List<int> fetchedEntries = new List<int>(); else if (!fetchedEntries.Contains(intNumber)) { lblMessage.Text = "Entry ID doesn't exist!"; lblMessage.ForeColor = Color.IndianRed; btnDeleteEntry.Enabled = false; } 
+4
source share
3 answers

The easiest way is to use the Contains method

 List<int> theList = GetListFromDatabase(); if (theList.Contains(theNumber)) { // It in the list } 

Your Q said this does not work for you. Could you give more information? The above template should work just fine

+17
source

Do you have an object that has an identifier or only identifiers?

If this is just an identifier, Contains() should work. Since you said that you did not do this, write down what you did.

If it is an object with id property, you can use Where()

 int userInput = 5; IList<T> myList = getList(); if(myList.Any(x => x.ID == userInput)) { // Has an ID } 
+1
source
 List<yourobject> sd = new List<yourobject>(); sd.Where(s=>s.id == <inputID>); 
-1
source

Source: https://habr.com/ru/post/1384953/


All Articles