Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq - how to map (select) deconstructed tuples?

I am trying to achieve a very simple thing. I have an Enumerable of tuples and I want to map and deconstruct them at the same time (as using .Item1, .Item2 is ugly as hell).

Something like this:

        List<string> stringList = new List<string>() { "one", "two" };

        IEnumerable<(string, int)> tupleList =
            stringList.Select(str => (str, 23));

        // This works fine, but ugly as hell
        tupleList.Select(a => a.Item1 + a.Item2.ToString());

        // Doesn't work, as the whole tuple is in the `str`, and num is the index
        tupleList.Select((str, num) => ...);
        // Doesn't even compile
        tupleList.Select(((a, b), num) => ...);
like image 848
eddyP23 Avatar asked Jun 11 '19 14:06

eddyP23


2 Answers

You can have named tuple members:

List<string> stringList = new List<string>() { "one", "two" };

// use named tuple members
IEnumerable<(string literal, int numeral)> tupleList =
    stringList.Select(str => (str, 23));

// now you have
tupleList.Select(a => a.literal + a.numeral.ToString());
// or
tupleList.Select(a => $"{a.literal}{a.numeral}");
like image 185
Cosmin Sontu Avatar answered Sep 29 '22 02:09

Cosmin Sontu


Option 1

var result = tupleList.Select(x=> { var (str,num)=x; return $"{str}{num}";})

Output

one23 
two23 

Option 2

If you are permitted to change the creation of tupleList, then you can do as following.

IEnumerable<(string str, int num)> tupleList = stringList.Select(str => (str, 23));
var result = tupleList.Select(x=>$"{x.str}{x.num}");

Option 2 eliminates the additional step required in Option 1.

like image 39
Anu Viswan Avatar answered Sep 29 '22 01:09

Anu Viswan