Get the Index of an Array in a C# For Loop

 
Written by Mark Pringle |
Published on:

This example shows how to get the index of an array in a C# for loop. I am using an ArrayList class to add objects to an array. You can add, remove, or search for array elements using an ArrayList. Since the ArrayList class is untyped, you can use it to store any element, including numbers, strings, and other objects. In the example below, we add speech parts to an ArrayList.

using System.Collections;

namespace ConsoleAppFun
{
    class Examples
    {
        static void Main()
        {
            ArrayList AddSyllables = new ArrayList();
            AddSyllables.Add("ia");
            AddSyllables.Add("riet");
            AddSyllables.Add("dien");
            AddSyllables.Add("ien");
            AddSyllables.Add("iet");
            AddSyllables.Add("iu");
            AddSyllables.Add("iest");
            AddSyllables.Add("io");
            AddSyllables.Add("ii");
            AddSyllables.Add("ily");
            AddSyllables.Add(@".oala\b");
            AddSyllables.Add(@".iara\b");
            AddSyllables.Add(@".ying\b");
            AddSyllables.Add(".earest");
            AddSyllables.Add(".arer");
           
            for (int i = 0; i < AddSyllables.Count; i++)
            {
                var value = AddSyllables[i];
                Console.WriteLine("Index = {0}; value = {1}", i, value);
            }
        }
    }
}

The result, when run in the Console App, looks like this.

get index of array in foreach c#

You can also use the object class instead of var, object value = AddSyllables[i];, to get the same results. 

Copyright © TravelDailyLife.com

Author: Mark Pringle
I'm just a guy who is addicted to the unfamiliar and who fulfills this addiction by traveling and writing about my travels. As a lover of sports, penning opinion articles related to sports is also a pastime.
My External Website (External Website Opens in New Window)

Comments

Please Login to Comment
No comments have been posted. Be the first.



Hire a Writer