Mark Needham

Thoughts on Software Development

Archive for the ‘foreach’ tag

C#’s Lambda ForEach: Only on Lists?

with 8 comments

One of my favourite things introduced into C# recently is the new ForEach method which can be applied to (apparently only!) lists.

Last week we had a situation where we wanted to make use of the ForEach method on an IDictionary which we were using to store a collection of Selenium clients.

1
IDictionary<string, ISelenium> seleniumClients = new Dictionary<string, ISelenium>();

We wanted to write a piece of code to exit all of the clients when our tests had completed. We thought the following would do the trick:

1
seleniumClients.Values.ForEach(client => client.Stop());

The problem is that code doesn’t actually compile!

‘seleniumClients.Values’ returns an ICollection which extends IEnumerable so we thought ForEach should be available.

We eventually got around the problem by putting the collection into a list and then applying the ForEach method but it seems like there should be a better way to do this.

1
new List<ISelenium>(seleniumClients.Values).ForEach(client => client.Stop());

Is there?

Written by Mark Needham

December 15th, 2008 at 11:52 pm

Posted in .NET

Tagged with , , ,