Have you ever had a collection of objects and wanted to produce a list of values based on the same property on each object? Unfortunately there hasn’t been a really elegant way of doing this other than looping through each element in the collection and building another collection manually containing the extracted properties.

Anyway – after being a little bit down on Action<T> I thought it would be neat to show a slightly more useful helper method on List<T>. The ConvertAll<T>(…) generic method on the List<T> takes a generic Converter<T> delegate which takes an input and returns an output. The idea is that you can use this to convert a list of objects to another list of objects.

Converter

I’m probably going to use this particular trick a lot more than Action<T>, and probably more for splitting off properties rather than doing straight object conversions – although that would be useful too. Although a bit of a wierd request it would be nice to short cut it even more so you could do this:

public TOutput SplitProperty<TOutput>(string propertyName);

Although the only way I think it could be done would be with reflection which would slow it down enormously. I’m keen to ask Joel Pobar at Code Camp this weekend what the performance difference between Reflection 1.1 and Reflection 2.0 is likely to be when they ship.

If you would like a copy of this code sample you can grab it from here.