[C#] lambda的foreach如何使用break/continue

3 mins.

在一般情況下,使用foreach時,遇到特定條件要讓他continue/break
會這樣去寫

1
2
3
4
5
6
List<string> lstSql;
foreach(var sql in lstSql)
{
if(string.IsNullOrEmpty(sql))
continue;//break;
}

但是在如果我們使用lambda還這樣寫,就會error

1
2
List<string> lstSql;
lstSql.Foreach(p=> if(stirng.IsNullOrEmpty(p)) continue;);

但我們又想要這樣做,該怎麼辦呢
必須知道lambda是怎麼處理foreach的

1
2
3
4
public static void ForEach<t>(this IEnumerable<t> sequence, Action<t> action)
{
foreach(var item in sequence) action(item);
}

由以上可以得知,我們下continue/break對function來說是看不懂的
我的作法是直接寫return,這樣就等於離開function

1
2
List<string> lstSql;
lstSql.Foreach(p=> if(stirng.IsNullOrEmpty(p)) return;);