advanced web statistics

List.ForEach Method & Delegate Trick

4/26/2007 11:56:18 PM

Andrew Robinson sent out an e-mail to our local .NET group about anonymous delegates.  The e-mail got me interested and I started reading up on delegates in the 2.0 framework. I am currently working on a class for a project that uses a lot of Generic lists.  While enumerating these lists I need to make changes to the collection and of course I am unable to make direct changes to the collection while I am enumerating (rightfully so!).  The next logical thing to do is create a copy and make changes and after enumerating commit those changes to the collection.  This entailed creating a method such as CopyList that would take a parameter of List<T> or simply an Object.

Two weeks ago I had a method that looked like the following.

static List<Bar> CopyFoo(Foo item)
{
   List<Bar> foo = new List<Bar>();

   foreach (Bar bar in item.Bar)
      foo.Add(bar);

   return foo;
}

Pretty basic stuff. The method takes the Foo object and enumerates each Bar in item. Each Bar is added to another collection of Bar. Pretty simple and straight-forward.  As simplistic as that looks, there is actually an easier, and in my opinion; more elegant way.

With the Generic List ForEach method you can dump the entire contents of a collection in one line!

static List<Bar> CopyFoo(Foo item)
{
   List<Bar> foo = new List<Bar>();

   item.Bar.ForEach(delegate (Bar bar) {foo.Add(bar);});

   return foo;
}

Very simple but a cool trick nonetheless.  The action of the ForEach method is a delegate to a method that performs an action (List.Add) on the object (Bar) passed to it.

.NET, C#, Interesting, Programming

kick it on DotNetKicks.com

Comments


Of course nowadays you can do:

item.Bar.ForEach(bar => foo.Add(bar));

Posted by: Maurits | 11/21/2007 6:43:01 AM

Very true Maurits. This is specific to 2.0.

Posted by: Will Asrari | 11/21/2007 1:09:15 PM

works very well !!!

Posted by: Prat | 5/14/2008 2:21:46 AM

cara, gostei muito do seu blog....

Posted by: Sites | 10/10/2008 9:01:04 PM

<quote>
item.Bar.ForEach(bar => foo.Add(bar));
</quote>

or even cleaner:

item.Bar.ForEach(foo.Add);

Posted by: jim | 12/3/2008 4:10:18 PM

Leave a Comment

   

  Enter the text to proceed!