Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a list to another list like in a functional programming language?

Tags:

c#

mapping

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)).

like image 396
John Threepwood Avatar asked Sep 01 '25 22:09

John Threepwood


2 Answers

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);
like image 114
I4V Avatar answered Sep 03 '25 14:09

I4V


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);
    }
}
like image 23
AlanT Avatar answered Sep 03 '25 13:09

AlanT