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

前端 未结 12 930
自闭症患者
自闭症患者 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:00

    bool @break = false;
    
    blackList.ForEach(item =>
     {  
        if(!@break && inputString.Contains(item))
         { @break = true;
           result = true;
         }
    
        if (@break) return;
        /* ... */
     });
    

    Note that the above will still iterate through each item but return immediately. Of course, this way is probably not as good as a normal foreach.

提交回复
热议问题