I often face the problem to convert the elements of a list to another list with the same elements transformed. Example:
List<string> numbers = ...;
List<int> parsedNumbers = new List<int>();
foreach(var n in numbers)
parsedNumbers.Add(parse(n));
Is it possible in C# to do this mapping in another easier way? Something like numbers.Map(x -> parse(x))
.
var parsedNumbers = numbers.Select(n=>int.Parse(n)).ToList();
You can also use List's ConvertAll
method.
var parsedNumbers = numbers.ConvertAll(n => int.Parse(n));
AND shorter versions
var parsedNumbers = numbers.Select(int.Parse).ToList();
var parsedNumbers = numbers.ConvertAll(int.Parse);
It looks like you want to use Select from Linq
using System.Linq;
[TestClass]
public class SelectFixture {
private static int Parse(string str) {
return int.Parse(str);
}
[TestMethod]
public void MapStringsToInts() {
var expected = new[] {1, 2, 3, 4, 5};
var strings = new List<string> { "1", "2", "3", "4", "5" };
var numbers = strings.Select(Parse).ToList();
CollectionAssert.AreEquivalent(expected, numbers);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With