使用拉姆达C#泛型出口的ForEach [英] c# exit generic ForEach that use lambda

查看:304
本文介绍了使用拉姆达C#泛型出口的ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道是否有可能退出使用拉姆达一个通用的ForEach?例如:

Does anyone know if it is possible to exit a generic ForEach that uses lambda? e.g.

someList.ForEach(sl =>
  {
    if (sl.ToString() == "foo")
        break;

    // continue processing sl here
    // some processing code
  }
);

这代码本身将无法编译。我知道我可以使用一个普通的foreach,但为了保持一致性我想使用的lambda。

This code itself won't compile. I know I could use a regular foreach but for consistency I want to use lambda.

非常感谢。

推荐答案

当然。但首先,请注意,我建议对本;我说一个序列运营商应该不会有副作用,并且声明应该有一个副作用。如果你在这的ForEach拉姆达做一些事情,然后使它在foreach循环体,而不是使它看起来像一个序列运算符的声明。

Sure. But first, note that I recommend against this; I say that a sequence operator should not have a side effect, and a statement should have a side effect. If you're doing something in that ForEach lambda, then make it a statement in the body of a foreach loop rather than making it look like a sequence operator.

这说,这里是你做了什么。首先,你自己写的任意序列的作品一个foreach,而不是仅仅列出:

That said, here's what you do. First, you write yourself a ForEach that works on arbitrary sequences, not just lists:

public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
    foreach(var item in sequence) action(item);
}

和现在你写你的休息是这样的:

And now you write your break like this:

someList
    .TakeWhile(x=>x.ToString() != "foo")
    .ForEach(sl=>
    {/*your action here*/});

这篇关于使用拉姆达C#泛型出口的ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆