Using foreach with Arrays (C# Programming Guide)
C# also provides the foreach statement. This statement provides a simple, clean way to iterate through the elements of an array. For example, the following code creates an array called numbers and iterates through it with the foreach statement:
int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 }; foreach (int i in numbers) { System.Console.WriteLine(i); }
With multidimensional arrays, you can use the same method to iterate through the elements, for example:
int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } }; foreach (int i in numbers2D) { System.Console.Write("{0} ", i); }
The output of this example is:
9 99 3 33 5 55
However, with multidimensional arrays, using a nested for loop gives you more control over the array elements.
One thing about the foreach statement that poses some problems for beginning developers lies with the expectation of what you can do in contrast to the normal for loop. One situation that demonstrates this difference is shown below:
// Wanting to remove items from a collection that meet a specific criteria
foreach (object item in this.Items)
{
if (item.ToString() == "Unimportant Item")
this.Items.Remove(item);
}
This will actually cause a runtime exception, complaining that you cannot modify the collection while iterating through it. This is an instance where the old-fashioned for loop can really help matters as shown below:
// Wanting to remove items from a collection that meet a specific criteria
for(int index=this.Items.Count; index > 0; index--)
{
if (this.Items[index-1].ToString() == "Unimportant Item")
this.Items.RemoveAt(index-1);
}
It is important to note that you work from end back to the front of the collection so as not to change your indexing of the collection. Also, in order to use the indexing method shown above the collection must implement IEnumerable and either the IList or ICollection interfaces or the collection can inherit from other index enabled base classes such as CollectionBase.
Actually, you can also loop forwards (more intuitive, IMHO) like this:
for (int index = 0; index < Item.Count; ++index)
{
if (Items[index].ToString() == "Unimporant item")
{
Items.RemoveAt(index);
--index;
}
}
The important part is remembering to decrement the index when you remove an item. It will be incremented again at the end of the loop so you'll basically remain at the same index.
Another alternative to this approach would be to use the foreach loop to generate a new collection of items to remove and then actually remove the items from the source collection. This however would be somewhat less efficient than actually using the for loop syntax.
- 7/7/2006
- Drew Noakes
- 3/17/2010
- Glen K
You can use "RemoveAll" and a Lambda expression to remove elements from a List:
public class Demo1
{
void Test01()
{
List<someElement> theList = new List<someElement>()
{
new someElement { currentState = "Normal", elementValue = 1 },
new someElement { currentState = "Delete", elementValue = 2 },
new someElement { currentState = "Delete", elementValue = 3 },
new someElement { currentState = "Delete", elementValue = 4 },
new someElement { currentState = "Normal", elementValue = 5 },
new someElement { currentState = "Normal", elementValue = 6 },
new someElement { currentState = "Normal", elementValue = 7 },
new someElement { currentState = "Delete", elementValue = 8 },
new someElement { currentState = "Normal", elementValue = 9 },
new someElement { currentState = "Delete", elementValue = 10 },
new someElement { currentState = "Normal", elementValue = 11 },
new someElement { currentState = "Delete", elementValue = 12 },
new someElement { currentState = "Delete", elementValue = 13 },
new someElement { currentState = "Delete", elementValue = 14 },
new someElement { currentState = "Delete", elementValue = 15 },
};
theList.RemoveAll( elementToRemove => { return elementToRemove.currentState.ToUpper().Equals( "DELETE" ); } );
}
//public class Demo1
class someElement
{
public String currentState { get; set; }
public Int16 elementValue { get; set; }
} //class someElement
- 9/21/2009
- Jelgab
List<object> toRemove = new List<object>();
foreach (object item in this.Items)
{
if (item.ToString() == "Unimportant Item")
toRemove.Add(item);
}
foreach (object item in toRemove)
{
this.Items.Remove(item);
}
- 5/19/2008
- Petro Protsyk