C# for loop with working example to download from GitHub

In this blog, I will show you different ways to use the C# for loop to count the number of records, display N number of records, display date range between two years and display random numbers. 

Simply put, the for keyword indicates a loop in C#. The loop will execute a block of code until a condition is false. You need to be careful when using a for loop so you do not run into an infinite loop.

So let's get started with the code below so you can see how it works.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Web.Controller.Helpers;

namespace Web.Controller.Controllers
{
    public class ForLoopController : System.Web.Mvc.Controller
    {
        [HttpGet]
        public ActionResult Home()
        {
            var drinks = ListOfBeverages.TopAlcoholicDrinksUk();

            //Loop over all drinks and count number
            int counterOne = 0;
            for (var i = 0; i < drinks.Count; i++)
            {
                counterOne++;
            }

            //Loop over all drinks and stop at 10
            List counterTwo = new List();
            for (var i = 0; i < drinks.Count; i++)
            {
                if (i < 10)
                {
                    counterTwo.Add(i);
                }
                else
                {
                    break;
                }

            }

            DateTime currentDate    = DateTime.Now;
            DateTime pastDate       = DateTime.Now.AddYears(-121);
            List yearList      = new List();
            //Loop over current date and get the last 121 years in Asc order
            for (int counter = pastDate.Year; counter <= DateTime.Now.Year; counter++)
            {
                yearList.Add(counter);
            }



            DateTime dt = new DateTime(1, 1, 1);

            TimeSpan span = currentDate - pastDate;
            int years = (dt + span).Year;

            List yearDesc = new List();
            //Loop over current date and get the last 121 years in Desc order
            for (int i = 0; i < years; i++)
            {
                yearDesc.Add(currentDate.AddYears(-i).ToString("yyyy"));
            }

            //Get 6 random numbers
            List lstNumbers = new List();
            lstNumbers.Clear();

            for (int i = 0; i <= 6; i++)
            {
                lstNumbers.Add(GetRandomRangeNumber(1, 10));
            }


            //Loop descending
            List lstNumbersDesc = new List();
            for (int i = 10; i > 0; i--)
            {
                lstNumbersDesc.Add(i);
            }

            TempData["allDrinks"]       = counterOne;
            TempData["firstTenDrinks"]  = counterTwo;
            TempData["LoopYears"]       = yearList;
            TempData["LoopYearsDesc"]   = yearDesc;
            TempData["LoopNumbersDesc"] = lstNumbersDesc;

            //Because we start at year 1 for the Gregorian calendar, we must subtract a year here.
            TempData["YearsText"]       = $"There are {yearList.Count - 1} years between {pastDate.Year} and {DateTime.Now.Year}";
            TempData["RandNumbers"]     = lstNumbers.OrderBy(x => x);

            //Get 6 random numbers and check for duplicates, if any found re-run the loop
            TempData["RandomNoDups"]    = GetRandonNUmbersNoDuplicates().OrderBy(x => x);

            return View();
        }

        private static readonly Random GetNewRandomNumber = new Random();

        private static int GetRandomRangeNumber(int min, int max)
        {
            lock (GetNewRandomNumber)
            {
                return GetNewRandomNumber.Next(min, max);
            }
        }

        private static List GetRandonNUmbersNoDuplicates()
        {

            List lstNumbers = new List();

            while (true)
            {
                for (int i = 0; i <= 6; i++)
                {
                    lstNumbers.Add(GetRandomRangeNumber(1, 10));

                }
                //Check for dups
                int lstdups = lstNumbers.GroupBy(x => x).Sum(x => x.Count() - 1);
                if (lstdups > 0)
                {
                    //If we have dupliacte numbers, clear the list and start again
                    lstNumbers.Clear();
                }
                else
                {
                    break;
                }
            }
            return lstNumbers;
        }
    }
}

Home Page.

The code below displays the C# for loop, in a production website, I would not be using TempData for the select list, I would use a ViewModel but for this simple example, TempData works fine.

@using System.Collections

<div class="container">
    <div class="row">
        <div class="col-3">

            <p>Number Of Drinks: @TempData["allDrinks"]</p>
            <p>return 0 to 9 or first 10</p>
            <ul>
                @foreach (var drink in (IEnumerable)TempData["firstTenDrinks"])
                {
                    <li>@drink</li>
                }
            </ul>
        </div>
        <div class="col-3">
            <p>@TempData["YearsText"]</p>
            <p>Years Asc</p>
            <select class="form-control" name="yearsAsc" id="yearsASc">
                @foreach (var year in (IEnumerable)TempData["LoopYears"])
                {
                    <option value="@year">@year</option>
                }
            </select>
            <p>Years Desc</p>
            <select class="form-control" name="yearsDesc" id="yearsDesc">
                @foreach (var year in (IEnumerable)TempData["LoopYearsDesc"])
                {
                    <option value="@year">@year</option>
                }
            </select>
        </div>
        <div class="col-3">
            <p>Return Random Numbers</p>
            <p>Keep refeshing page and you will notice you have duplicate numbers</p>
            <ul>
                @foreach (var rnd in (IEnumerable)TempData["RandNumbers"])
                {
                    <li>@rnd</li>
                }
            </ul>
        </div>
        <div class="col-3">
            <p>Return Random Numbers No Dups</p>
            <p>I use a while loop to achieve this</p>
            <ul>
                @foreach (var rnd in (IEnumerable)TempData["RandomNoDups"])
                {
                    <li>@rnd</li>
                }
            </ul>
        </div>
    </div>
    <div class="row">
        <div class="col-3">
            <p>Return Numbers Desc</p>
            <ul>
                @foreach (var lst in (IEnumerable)TempData["LoopNumbersDesc"])
                {
                    <li>@lst</li>
                }
            </ul>
        </div>
    </div>
</div>

Loop Descending.

As you can see from the examples above the C# for loop is very easy to use. When displaying the years in desc order I use the code below.

yearDesc.Add(currentDate.AddYears(-i).ToString("yyyy")); 

But you can also do descending order by using the code below, notice how the initializer; condition; iterator are different.

List lstNumbersDesc = new List();
            for (int i = 10; i > 0; i--)
            {
                lstNumbersDesc.Add(i);
            }

Summary.

I hope you found these examples of using C# loops helpful.