How to: Remove an item from a List<string>

gpuk360 picture gpuk360 · May 30, 2014 · Viewed 31.6k times · Source

How to: Remove an item from a List

I have got the following code snippet...

companies.Remove(listView_Test.SelectedItem.ToString());

There is a listView that contains (let's say) 3 items without a name, just with a Content of "A", "B" and "C". Now when I select an item of that listView, I secondly click on a button, which runs my method containing Remove()/RemoveAt(). Now I want to delete the line of the List<string> myList where the line is same to the Content of the selected item.

Edit: Solution by Flow Flow OverFlow

int index = companies.IndexOf(companyContent);
companies.RemoveAt(index);

Answer

Transcendent picture Transcendent · May 30, 2014

You have to get the index of the object you wanna remove from the list, then you can:

//Assuming companies is a list 
companies.RemoveAt(i);

To get the index of the item you can use :

companies.IndexOf("Item");

or use a for loop with conditional statements:

for (int i = 0; i < companies.Count; i++) {
   // if it is List<String>
   if (companies[i].equals("Something")) {
         companies.RemoveAt(i);   
   }
}