Is there a more elegant way to act on the first and last items in a foreach enumeration than count++
- by Edward Tanguay
Is there a more elegant way to act on the first and last items when iterating through a foreach loop than incrementing a separate counter and checking it each time?
For instance, the following code outputs:
>>> [line1], [line2], [line3], [line4] <<<
which requires knowing when you are acting on the first and last item. Is there a more elegant way to do this now in C# 3 / C# 4? It seems like I could use .Last() or .First() or something like that.
using System;
using System.Collections.Generic;
using System.Text;
namespace TestForNext29343
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
List<string> lines = new List<string>
{
"line1",
"line2",
"line3",
"line4"
};
int index = 0;
foreach (var line in lines)
{
if (index == 0)
sb.Append(">>> ");
sb.Append("[" + line + "]");
if (index < lines.Count - 1)
sb.Append(", ");
else
sb.Append(" <<<");
index++;
}
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
}
}