Saturday, August 14, 2010

♦ foreach loop sample

Figure 1: Output Screen

This example show how to easy use "foreach loop" instead of  "for...loop".

Syntax:
          foreach (type identifier in expression) statement
                       ( 1       2         in     3         )
where:


type

           The type of identifier.

identifier

           The iteration variable that represents the collection element. If the iteration variable is a value type,
            it is effectively a read-only variable that cannot be modified.

expression

            Object collection or array expression. The type of the collection element must be convertible to the
             identifier type. Do not use an expression that evaluates to null.

             Evaluates to a type that implements IEnumerable or a type that declares a GetEnumerator method. In the latter case, GetEnumerator should either return a type that implements IEnumerator or declares all the methods defined in IEnumerator.

statement

            The embedded statement(s) to be executed.
more info with msdn.microsof.com

Here this is example program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;

namespace @foreach
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string [] fruits = {"apple","kiwi","pineapple","mango"};
            foreach (string listFruits in fruits)
            {
                textBox1.Text += listFruits.ToString()+Environment.NewLine;
            }
            textBox1.Text += Environment.NewLine;
            textBox1.Text += "Lenght is " + fruits.Length;
        }
    }
}

No comments:

Post a Comment