Converting a List using a lambda expression

Here is a little construct I use when I need to convert a List<T> to a List<U> or when I need to pass a list of concatenated values as a string.
First, to convert a List<T> to a List<U> :

List<Guid> guidList = // Initialize list here or get it as a parameter or whatever :)
List<String> stringList = guidList.ConvertAll<String>(g => g.ToString());

It is really simple, I just use the ConvertAll method parameterized with the target type and pass it the lambda responsible for converting from the source type (Guid) to the target type (String). This example is obvious but the important thing is the combination of ConvertAll and a lambda.

For the second use ("passing a list of concatenated values as a string"), it is also really simple :
String stringValue = String.Join(
" separator ",
myGenericList.ConvertAll<String>(
/* Insert lambda here that return a string value */).ToArray());

The trick is simply to call ToArray on the converted list to be able to pass it to the String.Join method.

You can also use a extension method like this one :
public static class ListExtensions
{
public static String Join<T>(this List<T> list, string separator)
{
return String.Join(
separator,
list.ConvertAll<String>(t => t.ToString()).ToArray());
}
}

And then just write something like that:
static void Main(string[] args)
{
List<DateTime> list = new List<DateTime> { DateTime.Now, DateTime.Today };

String joinedList = list.Join(", ");
}


Happy coding :)

Popular posts from this blog

Handling exceptions the right way in WCF (part 2)

Adding a delay before processing Textbox events

Change the deployment URL of a ClickOnce application