我正在尝试实现一个非常简单的事情。我有一个可枚举的元组,我想同时映射和解构它们(如使用.Item1
,.Item2
一样丑陋)。
类似这样的东西:
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) => ...);
答案 0 :(得分:1)
选项1
var result = tupleList.Select(x=> { var (str,num)=x; return $"{str}{num}";})
输出
one23
two23
选项2
如果允许您更改tupleList的创建,则可以执行以下操作。
IEnumerable<(string str, int num)> tupleList = stringList.Select(str => (str, 23));
var result = tupleList.Select(x=>$"{x.str}{x.num}");
选项2消除了选项1所需的附加步骤。
答案 1 :(得分:1)
您可以命名元组成员:
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}");