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;
}
List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.
The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not.
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With