Converter<T> and ConvertAll(…)
April 19, 2005
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.
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.
Action<T> and ForEach(…)
April 19, 2005
In this post I am going to introduce you to the Action<T> generic delegate and how you can use it with the ForEach(…) method that is exposed on collection classes. In earlier posts on the Comparison<T> and Predicate<T> I showed how these new features could be put to good use to make your code more expressive. In this instance however I feel that the Action<T> delegate and the ForEach method are really only “sometimes code” – if you can refute that then please leave a comment – I’d love to hear about your use case.
For your reference, the Action<T> delegate is defined as:
public delegate void Action<T>(T obj);
We then pass an instance of this delegate into the ForEach(…) method of a generic collection class (like List<T>). What happens then is that each element in the collection is enumerated and passed as the argument to the delegate. So if you combined anonymous methods with this feature you would end up with the following code.
To me, that code doesn’t appear to be any more readable than the good old fashioned foreach(…) construct that you find in the VB.NET and C# languages (among others). So maybe the scenario I’ve chosen is wrong? Well, it turns out that the ForEach(…) method might be useful for those smaller inline pieces of logic, like printing something out to the screen.
I guess I’m still not convinced, but I would love to hear the opinion of other people. Anyway – you can download the code for this sample over at Project Distributor.