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

About Brian McKay
Software Architect

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: