C# for loop

C# for loop iterates through an array such as a List.

using System.Windows.Forms;
int sum = 0;
for (int i = 1; i < 5; i++)
{
sum += i;
}
MessageBox.Show(sum.ToString()); //sum=1+2+3+4=10

continue will skip one specific step, break will stop the loop.
using System.Windows.Forms;
int sum = 0;
for (int i = 1; i < 5; i++)
{
if (i == 2) continue;
sum += i;
}
MessageBox.Show(sum.ToString()); //sum=1+3+4=8
sum = 0;
for (int i = 1; i < 5; i++)
{
if (i == 2) break;
sum += i;
}
MessageBox.Show(sum.ToString()); //sum=1

Loops through a directory and get all files inside.
using System;
using System.IO;
ArrayList arrfiles = new ArrayList();
public void GetAllFileList(string dir)
{
DirectoryInfo di = new DirectoryInfo(dir);
FileInfo[] fi = di.GetFiles();
for (int i = 0; i < fi.Length; i++)
{
arrfiles.Add(fi[i].FullName);
}
DirectoryInfo[] disubs = di.GetDirectories();
for (int i = 0; i < disubs.Length; i++)
{
GetAllFileList(disubs[i].FullName);
}
}

Loops through all characters of a string.
using System.Windows.Forms;
string str = "csharp";
string str2 = "";
for (int i = 0; i < str.Length; i++)
{
str2 += str[i] + ", ";
}
MessageBox.Show(str2); //c, s, h, a, r, p,

Loops through a List.
using System.Collections.Generic;
using System.Windows.Forms;
List<string> lstr = new List<string>();
lstr.Add("Monday");
lstr.Add("Tuesday");
lstr.Add("Wednesday");
string str2 = "";
for (int i = 0; i < lstr.Count; i++)
{
str2 += lstr[i] + ", ";
}
MessageBox.Show(str2); //Monday, Tuesday, Wednesday,



endmemo.com © 2017  Terms of Use | Home