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));
}
}
}
Why not use
List<T>.RemoveAll()?If it’s not that simple (guessing it’s really not, you could try):
This saves you the cost of another list and multiple iterations.