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?
Comments
- Anonymous
June 25, 2008
PingBack from http://blog.a-foton.ru/2008/06/castingconverting-generic-list-of-a-certain-type-into-a-list-of-another-type-in-c/