How to: Remove an item from a List<string>
Solution 1
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);
}
}
Solution 2
You could either remove the item by its known position or by the contents in the item.
public static void Main()
{
List<Object> items = new List<Object>();
items.Add("test1");
items.Add("test2");
items.Add("test3");
foreach(var a in items)
Console.WriteLine(a.ToString());
Console.WriteLine("--");
items.RemoveAt(1); // remove object at position 1, in this case "test2"
foreach(var a in items)
Console.WriteLine(a.ToString());
Console.WriteLine("--");
items.RemoveAll(x => ((string) x) == "test1"); // LAMBDA query to remove by a condition
foreach(var a in items)
Console.WriteLine(a.ToString());
}
Output
test1
test2
test3
--
test1
test3
--
test3
Solution 3
public int FindItem(List<string> haystack, string needle)
{ for (int i = 0; i < haystack.Count; i++)
if (haystack[i] == needle) return i;
return -1;
}
try {
companies.Remove(FindItem(companies, listView_Test.SelectedItem.ToString() ) );
} catch { /* not found, no problem.. */ }
sjantke
Data Peonyr 💻 | Talend + Microsoft Certified 🚀 | Co-Founder of the Jantke Five 🏡
Updated on July 15, 2022Comments
-
sjantke almost 2 years
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 aContent
of "A", "B" and "C". Now when I select an item of thatlistView
, I secondly click on a button, which runs my method containingRemove()
/RemoveAt()
. Now I want to delete the line of theList<string> myList
where the line is same to theContent
of the selected item.Edit: Solution by Flow Flow OverFlow
int index = companies.IndexOf(companyContent); companies.RemoveAt(index);
-
sjantke almost 10 yearsWhat do you mean by "index of the object"? I do not know its position if you mean that. It is somewhere in the
List<string>
, I just know the "name". It is like "delete * from myList whereContent
= 'Hello World'". -
Dhaval Patel almost 10 yearsI think you have to cover RemoveRange also
-
sjantke almost 10 yearsThanks, that's what I'd like to do.
-
Tobia over 5 yearsIf you remove an item during the iterations the list size/count changes and the
i < companies.Count
condition doesn't guarantee to check all the list. Please try with a list of two removable items:{"Something","Something"}
-
Amos Egel over 5 years@Tobia So, would it be better to loop through the list in backward order, like
for (int i=(companies.Count-1); i>=0; i--)
? -
Tobia over 5 yearsYes, it can be a solution.