Search code examples
list.net-2.0

Remove items from list (.net 2.0)


I would like to remove items from a list that fulfill certain conditions. I made an example what I came up with so far:

//remove 1´s and 3´s from list of ints

List<int> indexes = new List<int>();
List<int> ints = new List<int>();
ints.Add(1);
ints.Add(2);
ints.Add(3);

foreach (int i in ints)
{
    if(i == 1 || i == 3)
    indexes.Add(ints.IndexOf(i));
}

indexes.Reverse();

foreach (int index in indexes)
{
    ints.RemoveAt(index);
}

I am curious if the solution can be optimized? I cannot use System.Linq, I have only found the System.Data.Linq namespace as reference (Visual Studio 2005)

UPDATE

I better had posted my real code. It is about deleting columns from a gridview

List<int> indexes = new List<int>();

foreach (Type type in types)
{
     foreach (DataControlField c in entriesGrid.Columns)
     {
          string header = c.HeaderText;
          if (header == type.Name)
          {
              indexes.Add(entriesGrid.Columns.IndexOf(c));
          }
     }
}

Solution

  • Why not use List<T>.RemoveAll()?

    ints.RemoveAll(IsOneOrThree); // Remove all 1's or 3's
    
    private static bool IsOneOrThree(int i)
    {
        return i == 1 || i == 3;
    }
    

    If it's not that simple (guessing it's really not, you could try):

    for(int i= ints.Count - 1; i >= 0; i--)
    {
        if(ints[i] == 1 || ints[i] == 3)
            ints.RemoveAt(i);
    }
    

    This saves you the cost of another list and multiple iterations.