Dav*_*mar 0 c# ienumerable foreach
我想在处理当前项目并迭代时访问下一个和上一个项目(如果在范围内)IEnumerable<object>
,它缺少索引器(据我所知)。
我不想需要一个List<object>
集合或一个数组来实现这一点,尽管这是我现在知道的唯一选择。
如果可能,我也更愿意避免使用 Linq 表达式。
目前我的方法是这样定义的:
public static void PrintTokens(IEnumerable<object> tokens)
{
foreach (var token in tokens)
{
// var next = ?
// var prev = ?
}
}
Run Code Online (Sandbox Code Playgroud)
您像往常一样执行循环,但是您当前所在的项目变为next
,前一个项目是current
,之前的项目是prev
。
object prev = null;
object current = null;
bool first = true;
foreach (var next in tokens)
{
if (!first)
{
Console.WriteLine("Processing {0}. Prev = {1}. Next = {2}", current, prev, next);
}
prev = current;
current = next;
first = false;
}
// Process the final item (if there is one)
if (!first)
{
Console.WriteLine("Processing {0}. Prev = {1}. Next = {2}", current, prev, null);
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 C# 7.0+,则可以编写
(prev, current, first) = (current, next, false);
Run Code Online (Sandbox Code Playgroud)
而不是循环末尾的三个单独的语句。
归档时间: |
|
查看次数: |
3287 次 |
最近记录: |