Thursday, June 11, 2009

Easy Syntax to Print List Elements

Create a list.
List <string> myList = new List <string> { "a", "b", "c", "d"};

a list-printing delegate :
Action <string> print = elem => { Console.WriteLine(elem);};

a statement:
myList.ForEach(print);



2 comments:

  1. Thanks for the tip which led me to aanother one.

    See
    http://stackoverflow.com/questions/371054/uses-of-action-delegate-in-c

    ReplyDelete
  2. this can actually be reduced to a one liner:
    myList.ForEach(x => {Console.WriteLine(x);});

    ReplyDelete