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
