Using LINQ ForEach To Populate Generic List in C# AND Enum to List

A C# trick I first had trouble wrapping my head around is using the LINQ ForEach operator to populate a list.  I was originally inspired by some source I found in the EXT.NET Icon building sample.   In addition to the ForEach lamda trick they included a very nice pattern for converting a c# Enum to a List.  So, let’s get right to the code.

 

enum Days { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };
static void Main(string[] args)
{
    List<string> daysOfWeekList = Enum.GetNames(typeof(Days)).ToList();
    daysOfWeekList.ForEach(a => Console.WriteLine(a));
}

 

That’s it!   Just another two patterns of using c# which helps me live cleaner in c#!

HTH’s.

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP since 2007. In addition, he's a multi-course video author at Pluralsight. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. Nice!

    There could be even more cleaner with:
    daysOfWeekList.ForEach(Console.WriteLine);

  2. James Curran says:

    How to you get 17 fewer keystrokes? It seems like a wash to me..

    foreach(var a in Enum.GetNames(typeof(Days))) {Console.WriteLine(a);}

    Enum.GetNames(typeof(Days)).ToList().ForEach(a=>Console.WriteLine(a));

  3. List.ForEach() is definitely simpler. One line of code vs. two. 17 fewer characters / keystrokes.

    I’ve been wanting this in C# for a long time. It’s very much like the Ruby .each method, which I loved while working on rails and miss in C#.

  4. Hi James,
    You make an excellent point. I guess this falls in the category of just because you can, does not mean you should.
    Thanks for pointing it out.
    -Peter

  5. James Curran says:

    You seem to be going to quite an effort just to use List.ForEach().

    foreach(var a in Enum.GetNames(typeof(Days)))
    Console.WriteLine(a);

    seems simpler. I know everyone loves lambdas, but using a lambda for its own sake is not good programming. I don’t think I’ve ever seen a use of List.ForEach which improved on using a simple foreach() statement. Particularly in cases like this, which require taking a perfectly good IEnumerable and needlessly build a List out of it.

Follow

Get every new post delivered to your Inbox

Join other followers: