Is there a shortcut to call a method on every element in a list/array or do you have to perform a loop and call each time? RRS feed

  • Question

  • Basically, instead of doing this...

    for (int i = 0; i < MyList.Count; i++) {

    Is there a way to do this? (I know the following won't work but something along those lines.)


    Tuesday, April 30, 2019 10:14 PM


  • You can use .ForEach

    List<string> myList = new List<string>() {"Karen", "Jim","Bob"};
    myList.ForEach(name => Console.WriteLine(name.ToUpper()));


    List<string> myList = new List<string>() {"Karen", "Jim","Bob", "Kim"};
    myList.ForEach(name =>
        if (name.StartsWith("K"))
    Is this what you are looking for?

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    profile for Karen Payne on Stack Exchange

    • Marked as answer by T Gregory Tuesday, April 30, 2019 10:56 PM
    Tuesday, April 30, 2019 10:51 PM