Is there way to find out when I'm at the first and last loop on a foreach?
foreach(string str in list){
if(str.isFirst(list) == true){...}
if(str.isLast(list) == true){...}
}
^ Something like this?
Is there way to find out when I'm at the first and last loop on a foreach?
foreach(string str in list){
if(str.isFirst(list) == true){...}
if(str.isLast(list) == true){...}
}
^ Something like this?
for (int i = 0; i < list.Length; i++)
{
if (i == 0)
{
// is first iteration
}
if (i >= list.Length - 1)
{
// is last iteration
}
}
Use a counter
int i = 0;
foreach(string str in list)
{
if(i == 0) { /* first */ }
if(i == list.Count - 1) { /* last */ }
i++;
}
The simplest way to check whether you are process the first or last item would be the following code :
void Process(string[] strings)
{
for (int i = 0; i < strings.Length; i++)
{
var s = strings[i];
bool isFirst = i == 0;
bool isLast = i == strings.Length - 1;
}
}
Alternative way
foreach(var kv in list.ToDictionary(k => list.IndexOf(k), v => v))
{
if (kv.Key == 0) Console.WriteLine("First is {0}", kv.Value);
if (kv.Key == list.Count - 1) Console.WriteLine("Last is {0}", kv.Value);
}
The best option is a for() cycle anyway
bool first = true;
foreach(string str in list)
{
if(first)
{
//do something
first = false;
}
}