Fil*_*sen 88
我喜欢Linq的方式,但没有Skip(1),这样你也可以用它作为列表中的最后一项,你的代码仍然是干净的imho :)
foreach(var item in items)
{
if (items.First()==item)
item.firstStuff();
else if (items.Last() == item)
item.lastStuff();
item.otherStuff();
}
Run Code Online (Sandbox Code Playgroud)
geo*_*tnz 26
像这样的东西:
bool first = true;
foreach(var item in items)
{
if (first)
{
item.firstStuff();
first = false;
}
item.otherStuff();
}
Run Code Online (Sandbox Code Playgroud)
Ani*_*Ani 15
这是一个高性能的解决方案:
using (var erator = enumerable.GetEnumerator())
{
if (erator.MoveNext())
{
DoActionOnFirst(erator.Current);
while (erator.MoveNext())
DoActionOnOther(erator.Current);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:这是一个LINQ之一:
if (enumerable.Any())
{
DoActionOnFirst(enumerable.First());
foreach (var item in enumerable.Skip(1))
DoActionOnOther(item);
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果项目上的操作具有可分配的签名Func<TItem, TResult>
,您可以执行以下操作:
enumerable.Select((item, index) => index == 0 ? GetResultFromFirstItem(item) : GetResultFromOtherItem(item));
Run Code Online (Sandbox Code Playgroud)
bool first = true;
foreach(var foo in bar)
{
if (first)
{
// do something to your first item
first = false;
}
// do something else to the rest
}
Run Code Online (Sandbox Code Playgroud)
在我看来这是最简单的方法
foreach (var item in list)
{
if((list.IndexOf(item) == 0)
{
// first
}
// others
}
Run Code Online (Sandbox Code Playgroud)