In this source code example, we will demonstrate the usage of List ConvertAll in C#.
The ConvertAll method converts the elements in the current List to another type and returns a list containing the converted elements.C# List ConvertAll example
In the example, we have a list of fruits. We convert the list to two other lists.using System;
using System.Collections.Generic;
public class ListDemo
{
public static void Main(string[] args)
{
var fruits = new List<string> { "banana", "mango", "apple", "watermelon" };
List<string> uppedFruits = fruits.ConvertAll(s => s.ToUpper());
List<int> lengths = fruits.ConvertAll(s => s.Length);
foreach(string f in fruits) {
Console.WriteLine(f);
}
foreach(int l in lengths) {
Console.WriteLine(l);
}
}
}
Output:
banana
mango
apple
watermelon
6
5
5
10
Related C# List Examples
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course