Deleting items in a list

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

My app populates a list of custom objects from data fetched from a database.

What i want to do now is filter the list and remove items from the list that
don't match the filter criteria.

I was thinking of using foreach to traverse the list and dynamically remove
items that fail the filter however I am having difficulty removing an item
from the list as i don't know its postion in the list.

Can anyone tell me how to do this as i want to avoid creating another list
to hold filtered items.

Thanks
Macca
 
1.1 or 2.0?

In 2.0 you can use a predicate and List<T> to do this for you; just replace
"int" with your class, and the test with your "delete me" condition...

static void Main(string[] args)
{
// add some dummy data
List<int> numbers = new List<int>();
for (int i = 1; i < 20; i++)
numbers.Add(i);

// remove everything that is divisible by 3
numbers.RemoveAll(delegate(int testItem)
{
// remove true if we meet the condition, i.e.
// those that we want to remove
return testItem % 3 == 0; // divisible by 3 => true
});

// look at what is left;
foreach (int item in numbers)
{
Console.WriteLine(item);
}
}
 
Back
Top