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) => ...);
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}");
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.
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