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

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

    Would this work for you:

    bool result = null != blackList.Find( item => inputString.Contains(item)) );
    
    0 讨论(0)
  • 2020-12-14 15:13
    blackList.ForEach(new Action<string>(
        delegate(string item)
        {
            if(inputString.Contains(item)==true)
            {
                result = true;
                // I want to break here
                return;
            }
        }
    ));
    
    0 讨论(0)
  • 2020-12-14 15:14

    The only way to "exit" the loop is to throw an exception. There is no "break" style way of exiting the .ForEach method like you would a normal foreach loop.

    0 讨论(0)
  • 2020-12-14 15:15
        class Program
    {
        static void Main(string[] args)
        {
            List<string> blackList = new List<string>(new[] { "jaime", "jhon", "febres", "velez" });
            string inputString = "febres";
            bool result = false;
            blackList.ForEach((item) =>
                                  {
                                      Console.WriteLine("Executing");
                                      if (inputString.Contains(item))
                                      {
                                          result = true;
                                          Console.WriteLine("Founded!");
                                      }
                                  },
                              () => result);
            Console.WriteLine(result);
            Console.ReadLine();
        }
    
    
    }
    public static class MyExtensions
    {
        public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action, Func<bool> breakOn)
        {
            foreach (var item in enumerable)
            {
                action(item);
                if (breakOn())
                {
                    break;
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-14 15:16

    The ForEach method is not mean to do this. If you want to know if a collection contains an item you should use the Contains method. And if you want to perform a check on all items in a collection you should try the Any extention method.

    0 讨论(0)
  • 2020-12-14 15:17

    Do you have LINQ available to you? Your logic seems similar to Any:

    bool any = blackList.Any(s=>inputString.Contains(s));
    

    which is the same as:

    bool any = blackList.Any(inputString.Contains);
    

    If you don't have LINQ, then this is still the same as:

    bool any = blackList.Find(inputString.Contains) != null;
    

    If you want to run additional logic, there are things you can do (with LINQ) with TakeWhile etc

    0 讨论(0)
提交回复
热议问题