Home > Undefined > Remove items from a list.

Remove items from a list.

December 9th, 2009

You have a list of “something” and you want to remove items from the list. I can think of a couple ways to do this.

Remove Items V1:
List myList = new List() { "one", "two", "three" };
// print out the original list
foreach (string item in myList)
Console.WriteLine(item); // one two three

myList.Remove("two");

// print out the new list
foreach (string item in myList)
Console.WriteLine(item); // one three

Remove Items V2:
List myList = new List() { "one", "two", "three" };
// print out the original list
foreach (string item in myList)
Console.WriteLine(item); // one two three

myList = myList.Expect(i => i == "two");

// print out the new list
foreach (string item in myList)
Console.WriteLine(item); // one three

Notes:
The rules for a foreach loop don’t allow you to delete or nullify an object in the collection during the looping, so you need to remove items more directly. For complete objects, this can be a bit harder. Leveraging LINQ can make the task much easier. With the second example, you could use any property/method within the complex object for your comparison. E.G.: IsDirty or ItemFlaggedForDelete().

Tags: ,
Comments are closed.