how do I check if an entity is the first element of a foreach loop
I like the Linq way, but without the Skip(1), this way you can also use it for the last item in a list and your code remains clean imho :)
foreach(var item in items)
{
if (items.First()==item)
item.firstStuff();
else if (items.Last() == item)
item.lastStuff();
item.otherStuff();
}
There are several ways that you could do that.
- Use a
for
loop instead - Set a Boolean flag
- Use Linq to get the
list.First()
and thenforeach
overlist.Skip(1)
Something like this:
bool first = true;
foreach(var item in items)
{
if (first)
{
item.firstStuff();
first = false;
}
item.otherStuff();
}
Here's a performant solution:
using (var erator = enumerable.GetEnumerator())
{
if (erator.MoveNext())
{
DoActionOnFirst(erator.Current);
while (erator.MoveNext())
DoActionOnOther(erator.Current);
}
}
EDIT: And here's a LINQ one:
if (enumerable.Any())
{
DoActionOnFirst(enumerable.First());
foreach (var item in enumerable.Skip(1))
DoActionOnOther(item);
}
EDIT: If the actions on the items have signatures assignable to Func<TItem, TResult>
, you can do:
enumerable.Select((item, index) => index == 0 ? GetResultFromFirstItem(item) : GetResultFromOtherItem(item));
In my opinion this is the simplest way
foreach (var item in list)
{
if((list.IndexOf(item) == 0)
{
// first
}
// others
}