Wednesday, August 08, 2007

Dotnet 2.0 Generic Lists

So I am working in .Net 2.0 and have to deal with a lot of generic List<t> types. I have been using anonymous delegates to find items in them since I am not in .Net 3.5 and can’t use lambda expressions. So for example if I need to get one item out of the list I simply use the following code...

<t> = List<t>.Find(predicate<t>) or for some code

String dogName = "Max";
List<Dog> dogs = some list of dogs;
Dog aDog = dogs.Find(delegate (Dog match)
{
return match.name.Equals(dogName);
});

That will return the first dog in the list that is named Max.

There are many operations you can do this way and none of this is all that new or really interesting, except I came across ForEach(Predicate<T>).

To use this, it is List<t>.ForEach(Predicate<t>).

So I found it interesting that they would include the ForEach on the list. I started a message post at work asking about this. When should you use the list ForEach vs. the regular foreach. Is one better than the other and what not.

Geoff shared that by using ForEach looping becomes a natural part of the list and it reduces the amount of code that needs to be written. Grant took it one step further in summing up Geoff's response.

He states "Imagine you want to be able to talk about solving problems using some sort of “natural” set based language. The chained delegates *do* this, and in doing so reduce boilerplate code. Still, the question of why do this at all, why bother, why does this exist, why solve problems this way exists. The answer is *list comprehensions*; and it is well worth the read."

You can find out more about List Comprehensions here.

I am not going to lie and say I understand List Comprehension fully, however my point of the story is I like that when I ask the people I work with a question about why use a ForEach instead of a foreach, the discussion ends with a lesson on list comprehension.

By the way, I can't wait for Lambda Expressions in .Net 3.5.

----------------
Now playing: Amy Winehouse - You Know I'm No Good
via FoxyTunes

No comments: