加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Linq – lookahead迭代

发布时间:2020-12-15 03:58:34 所属栏目:百科 来源:网络整理
导读:我通过使用访问者类型模式的集合来迭代,需要访问列表中的当前和下一个项目.目前我正在通过这样的扩展方法来做 public void VisitTItem(this IEnumerableTItem theList,ActionTItem,TItem visitor){ for (i = 0; i = theList.Count - 1; i++) { if (i == theL
我通过使用访问者类型模式的集合来迭代,需要访问列表中的当前和下一个项目.目前我正在通过这样的扩展方法来做
public void Visit<TItem>(this IEnumerable<TItem> theList,Action<TItem,TItem> visitor)
{
    for (i = 0; i <= theList.Count - 1; i++) {
        if (i == theList.Count - 1) {
            visitor(theList(i),null);
        } else {
            visitor(theList(i),theList(i + 1));
        }    
    }    
}

我想知道是否有其他/更好/更优雅的方式来实现这一点?目前,我认为我只需要访问列表中的当前和下一个项目,但我想知道是否可能会遇到需要查看下一个“n”项目的情况.

解决方法

假设你使用的是.NET 4,你可以使用Zip来完成同样的事情:
var query = original.Zip(original.Skip(1),(current,next) => new { current,next });

这将遍历序列两次.一个更好的替代您当前的扩展方法(我不相信将工作,btw,因为IEnumerable没有Count属性,你正在尝试调用该列表作为一个方法…)将是一些东西喜欢:

public static void Visit<TItem>(this IEnumerable<TItem> theList,TItem> visitor)
{
    TItem prev = default(TItem);
    using (var iterator = theList.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            return;
        }
        prev = iterator.Current;
        while (iterator.MoveNext())
        {
            TItem current = iterator.Current;
            visitor(prev,current);
            prev = current;
        }
    }
    visitor(prev,default(TItem)); // Are you sure you want this?
}

更一般的前瞻是棘手的,说实话…你想要一些循环缓冲区,我怀疑…可能是一个自定义集合.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读