AGuyCalledGerald
AGuyCalledGerald

Reputation: 8150

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));
          }
     }
}

Upvotes: 1

Views: 279

Answers (3)

Dimi
Dimi

Reputation: 1

A more granular example for RemoveAll can be found below (links to .NET 2.0):

List<T>.RemoveAll Method

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245429

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.

Upvotes: 4

robbrit
robbrit

Reputation: 17960

Try RemoveAll:

public bool MyPredicate(int i){
  return i == 3 || i == 5;
}

ints.RemoveAll(MyPredicate);

or if you have access to anonymous delegates:

ints.RemoveAll( (i) => i == 3 || i == 5 );

In addition, it is not usually a good idea to remove your question from SO, so that in the future people who might have the same question can read and learn from this.

Upvotes: 0

Related Questions