Home > .NET, C# 2.0 > C# foreach howto.

C# foreach howto.

January 16, 2007

I was getting sick of doing for loops so I decided to read up on the foreach statement. The foreach statement is small, clean, quick and much easier to read if you ever plan on having a programmer help you out with your coding. There is no need for me to ramble on so check out this code. The foreach statement basically lets you define an object, and loop through a collection of the same object type.

This simple example “checks” all the check boxes for all the items in a ListViewControl.

foreach (ListViewItem lvi in lvTBS.Items)
{
    lvi.Checked = true;
}

This is way better than doing this:

for ( i=0; i<=ListViewControl.Items.Count(); i++ )
{
    ListViewItem lvi = ListViewControl.Items[i];
    lvi.Checked = true;
}
Advertisement
Categories: .NET, C# 2.0
  1. January 16, 2007 at 11:47 am

    I will gladly ramble a bit though! foreach is a great approach in many cases, and is definitely easier to read. And you can use break; to leave the foreach loop at any time. If you need to process the index number of an element, it is not the right choice, the old for is still the best for that, but most of the time that is not the case and foreach is a preferred replacement in my book.

    To really get the most out of it, you must understand that it feeds off of an IEnumerable implementation. Anything that implements an IEnumerable interface can be used in a foreach statement, which means you can write your own class members that will also be consumable by foreach.

  2. reza
    April 26, 2011 at 2:07 pm

    hello
    my name is reza azimi from Isfahan-Iran
    Thank you From Manager @ Designer This Site

  1. No trackbacks yet.
Comments are closed.
%d bloggers like this: