在foreach循环中,有没有一种方法可以确定当前所在的行?

5

I have this code:

foreach (var row in App.cardSetWithWordCounts)
{
   details.Children.Add(new SeparatorTemplate());
   // do some tasks for every row 
   // in this part of the loop ...
}

我不想在第一次运行foreach时添加SeparatorTemplate,但我想执行其他任务。请问有什么建议吗?

我希望在foreach中执行其余的代码,但第一次循环时不执行添加模板的那一行。

5个回答

11

如果你想跳过第一行,可以使用Skip

foreach (var row in App.cardSetWithWordCounts.Skip(1))

如果您想要知道确切的行号,请使用Select重载:

foreach (var x in App.cardSetWithWordCounts.Select((r, i) => new { Row = r, Index = i })
{
    // use x.Row and x.Index
}

2
Linq非常有用,不是吗。没有IEnumerable的生活就不一样了。 - Blue
抱歉,也许我表达不够清楚。我想在foreach循环中执行其余的代码,但第一次循环时不执行添加模板的那一行。 - Alan2
2
那么,在第一次循环中,您可以检查x.Index == 0,对代码进行相应的执行。 - Patrick Hofman

2
最简单的方法是:
bool isFirstRun = true;
foreach (var row in App.cardSetWithWordCounts)
{
    if(isFirstRun)
        isFirstRun = false;
    else
        details.Children.Add(new SeparatorTemplate());

    // do some tasks for every row 
    // in this part of the loop ...    
}

1
var firstRow = true;

foreach(var row in App.cardSetWithWordCounts)
{
    if(firstRow) 
    {
        firstRow = false;
    }
    else
    {
        // rest of the code here
    }   
}

1
你可以尝试创建一个扩展方法。 Action 的第二个参数是迭代器的索引。
public static class ExtenstionArray
{
    public static void ForEach<T>(this IEnumerable<T> sequence, Action< T, int> action)
    {
        int i = 0;
        foreach (T item in sequence)
        {
            action(item,i);
            i++;
        }
    }
}

然后像这样使用。
App.cardSetWithWordCounts.ForEach((i, idx)=>{
    if(idx == 0){
        details.Children.Add(new SeparatorTemplate());
    }
    // other logic
});

c#在线


1
您可以使用Skip方法来实现此目的:
foreach (var row in App.cardSetWithWordCounts.Skip(1))

更新:
foreach (var row in App.cardSetWithWordCounts.Select((c, index) => new { Row = c, Index = index })
{
    if(row.Index != 0)
}

只要不要忘记在您的using指令中添加以下行:

using System.Linq;

抱歉,也许我表达不够清楚。我想在foreach循环中执行代码的其余部分,但第一次循环时不执行添加模板的那一行。 - Alan2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接