Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if List<T> contains specified integer number [closed]

Tags:

c#

.net

arraylist

I am using List<T> array to store all ID's that I have read from my database file.

do lets say I have ID: 5, 8, 15

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

How do I do this?

I have tried using Contains or Find, but I cannot manage to make it work.

Bit of the code which doesn't seem to wok. It only shows Entry ID doesn't exist! only if I enter a 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;
    }
like image 694
HelpNeeder Avatar asked Dec 06 '11 16:12

HelpNeeder


People also ask

How do you check whether a List contains a specified element?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.

How do I see if a List contains a List?

The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not.


2 Answers

The easiest way is to use the Contains method

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

Your Q said this isn't working for you though. Could you give some more information? The above pattern should work just fine

like image 131
JaredPar Avatar answered Sep 23 '22 14:09

JaredPar


Do you have an object which has an ID or just the IDs?

If it's just the ID, Contains() should work. Since you said it didn't, post what have you done.

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

int userInput = 5;
IList<T> myList = getList();

if(myList.Any(x => x.ID == userInput)) {
     // Has an ID
}
like image 35
Ortiga Avatar answered Sep 23 '22 14:09

Ortiga