How do i exit a List.ForEach loop when using an anonymous delegate?

前端 未结 12 906
自闭症患者
自闭症患者 2020-12-14 14:24

In a normal loop you can break out of a loop using break. Can the same be done using an anonymous delegate?

Example inputString and result are both declared outside

12条回答
  •  轮回少年
    2020-12-14 15:04

    if you realy want to exist a loop foreach in a list you could use the exception like this code:

    public class ExitMyForEachListException : Exception
    {
        public ExitMyForEachListException(string message)
            : base(message)
        {
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List str = new List() { "Name1", "name2", "name3", "name4", "name5", "name6", "name7" };
            try
            {
                str.ForEach(z =>
                {
                    if (z.EndsWith("6"))
                        throw new ExitMyForEachListException("I get Out because I found name number 6!");
                    System.Console.WriteLine(z);
                });
            }
            catch (ExitMyForEachListException ex)
            {
                System.Console.WriteLine(ex.Message);
            }
    
            System.Console.Read();
        }
    }
    

    hope this help to get other point of view.

提交回复
热议问题