List.ForEach Method

I think I’ve posted something related to this before, but it’s worth another look.  Use List().ForEach() to easily execute code inline.

        static void Main(string[] args)
        {
            List<int> myList = new List<int>() { 1, 2, 3, 4 };

            foreach (var i in myList)
                Console.WriteLine(i.ToString());

            Console.ReadLine();
        }

Becomes:

        static void Main(string[] args)
        {
            new List<int>() { 1, 2, 3, 4 }.ForEach(x => Console.WriteLine(x));
            Console.ReadLine();
        }
Advertisements