For Each Loop in C# .NET
Submitted by Yorkiebar on Friday, August 22, 2014 - 23:47.
Introduction:
This tutorial will be on how to use a 'foreach' loop in C# .NET.
ForEach:
A ForEach loop in C# is used to iterate through a list of elements held within one location. An example of this could be a list of usernames which are allowed to login to the program. This is what example we are going to be using in this tutorial.
Theory:
I am going to create a C# Console Application which will do the following;
Ask the user for a name.
Create a list of accepted usernames.
Use a foreach loop to iterate through each of the accepted usernames.
Output the result.
Application - Username:
So first, we want to ask the user for their username. We are simply going to output a message using the 'console.writeline' namespace/method asking the user for their username, then use the 'readline' method to put their entry in to a new 'username' string variable...
Application - Accepted:
Now we want to create a list of accepted usernames. This will be a simple single dimensional string array, like so...
This would allow the entry of 'user' or 'admin' in to the application.
Application - For Each:
Before we begin iterating through the accepted usernames to check if the user is accepted. We want to create a boolean to hold whether they are accepted or not, we'll call this 'acc'...
The next thing we want to do is iterate through the accepted usernames and compare it to the entered username from the user held within our 'username' string variable...
Now we will have the boolean variable 'acc' as 'true' if the user is accepted. We can use this later like so...
Finished!
Here is the full source code...
- Console.Writeline("Enter your username: ");
- string username = Console.ReadLine();
- string[] accepted = {"user", "admin"};
- bool acc = false;
- foreach (string s in accepted) {
- if (s.ToLower() == username.ToLower()) {
- acc = true;
- break;
- }
- }
- if (acc) {
- Console.WriteLine("Accepted!");
- }else
- Console.WriteLine("You're not accepted!");
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Foreach
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Enter your username: ");
- string username = Console.ReadLine();
- string[] accepted = {"user", "admin"};
- bool acc = false;
- foreach (string s in accepted) {
- if (s.ToLower() == username.ToLower()) {
- acc = true;
- break;
- }
- }
- if (acc) {
- Console.WriteLine("You're accepted!");
- }else{
- Console.WriteLine("You're not accepted!");
- }
- }
- }
- }
Add new comment
- 44 views