Welcome to MSDN Blogs Sign in | Join | Help

Casting/converting generic List of a certain type into a List of another type in C#

Here’s an easy way to convert a generic List of a specific type to a List of another type.

List<double> listOfDoubles = new List<double>() {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9};

List<int> listOfIntegers = listOfDoubles.ConvertAll(doubleNumber => (int) doubleNumber);

listOfIntegers.ForEach(Console.WriteLine);

Sure, this example only casts doubles to integers (useless), but you could do the same for more complex conversions for reference classes (i.e, convert a list of Employee instances to a list of their salaries as a decimals).

Note how beautiful the code looks like with the usage of the lambda expression … isn’t C# 3.0 the coolest thing ever?

Published Wednesday, June 25, 2008 6:36 PM by minguyen

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# a-foton &raquo; Casting/converting generic List of a certain type into a List of another type in C#

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker