- Home /
How do you check if a string has already been removed from a generic list?
I use javascript.
How do you check if a string has already been removed from a generic list? i have an if statement:
if(Master.ether == 0){
Master.itembag.Remove("Ether");
}
and it keeps trying to remove the string "Ether" from the list once it is 0. i need it to happen once only. i know i can make a toggle type tidbit of code with.. but is there a method for searching generic list for specific strings?
Answer by asafsitner · Jan 24, 2013 at 10:46 AM
You're looking for **Contains**.
As in
if(Master.ether == 0 && Master.itembag.Contains("Ether"))
{
Master.itembag.Remove("Ether");
}
or
if(Master.ether == 0)
{
if(Master.itembag.Contains("Ether"))
{
Master.itembag.Remove("Ether");
}
}
EDIT
It's worth noting that List.Contains
performs a linear search and thus has complexity of O(n)
where n
is the number of elements in the list. This means that as the list grows longer, searching it becomes slower. It shouldn't be an issue as long as your list is relatively small though.
On the other hand, if you want you could implement your inventory using a Dictionary or Hashtable, both of which you can do ContainsKey
search that is always O(1)
, meaning they can instantly find the key regardless of the collection size. Obviously this is far more optimized, but potentially more cluttered to work with.
For our specific inventory case though I believe it will be the better approach all around, as you could specify the dictionary key as the item name and the value as the number of items the inventory contains.
Thanks a tons thats exactly what i wanted to know. Also, my list is definately going to be at most around 10 items i size. So it should be a quick search im guessing. However, If i ever create a larger inventory I will definately read up on Dictionaries and Hashtables. Thanks again.