none
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++) {
    
        MyList[i].MyMethod();
    
    }


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

    MyList.MyMethod();


    Tuesday, April 30, 2019 10:14 PM

Answers

  • You can use .ForEach

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

    And

    List<string> myList = new List<string>() {"Karen", "Jim","Bob", "Kim"};
    myList.ForEach(name =>
    {
        if (name.StartsWith("K"))
        {
            Console.WriteLine(name);
        }
    });
    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.

    StackOverFlow
    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
    Moderator