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();
}
}
}
Your current example can be done without iterating.
Console.WriteLine(">>> " + String.Join(lines, ", ") + " <<<);
If you're just iterating I find it easier to just replace it with a regular for loop and check the boundaries.
for(int i=0; i<list.count; i++)
{
if(i == 0)
//First one
else if(i == list.count -1)
//Last one
}
It'll be a lot faster than using the .First() and .Last() extension methods. Besides, if you have two items in your list with the same (string) value comparing to Last or First won't work.