列出 ForEach [英] List ForEach break

查看:13
本文介绍了列出 ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法跳出 foreach 扩展方法?break"关键字无法将扩展方法识别为有效的中断范围.

is there a way to break out of the foreach extension method? The "break" keyword doesn't recognize the extension method as a valid scope to break from.

//Doesn't compile
Enumerable.Range(0, 10).ToList().ForEach(i => { System.Windows.MessageBox.Show(i.ToString()); if (i > 2)break; });

<小时>

从问题中删除了linq"


removed "linq" from question

请注意,代码只是一个示例,用于显示 break 在扩展方法中不起作用……我真正想要的是用户能够中止处理列表……UI 线程有一个 abort 变量和 for当用户点击取消按钮时,循环就会中断.现在,我有一个正常的 for 循环,但我想看看是否可以使用扩展方法.

note the code is just an example to show break not working in the extension method... really what I want is for the user to be able to abort processing a list.. the UI thread has an abort variable and the for loop just breaks when the user hits a cancel button. Right now, I have a normal for loop, but I wanted to see if it was possible to do with the extension method.

推荐答案

将其称为 List Foreach 与 LINQ 可能更准确.

It's probably more accurate to call this a List<T> Foreach vs. a LINQ one.

无论哪种情况,都无法跳出这个循环.主要是因为它实际上并不是一个循环.这是一个方法,它接受一个在循环内调用的委托.

In either case though no there is no way to break out of this loop. Primarily because it's not actually a loop per say. It's a method which takes a delegate that is called inside a loop.

虽然创建具有中断功能的 ForEach 相当简单

Creating a ForEach with break capability is fairly straight forward though

public delegate void ForEachAction<T>(T value, ref bool doBreak);
public static void ForEach<T>(this IEnumerable<T> enumerable, ForEachAction<T> action) {
    var doBreak = false;
    foreach (var cur in enumerable) {
        action(cur, ref doBreak);
        if (doBreak) {
            break;
        }
    }
}

然后你可以重写你的代码如下

You could then rewrite your code as the following

Enumerable.Range(0,10)
    .ForEach((int i,ref bool doBreak) => {
        System.Windows.MessageBox.Show(i.ToString()); 
        if ( i > 2) {doBreak = true;}
    });

这篇关于列出 ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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