Linq - 如何映射(选择)解构元组?

edd*_*P23 10 c# linq dictionary tuples

我正在努力实现一件非常简单的事情。我有一个 Enumerable 元组,我想同时映射和解构它们(因为使用.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) => ...);
Run Code Online (Sandbox Code Playgroud)

Cos*_*ntu 5

您可以命名元组成员:

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}");
Run Code Online (Sandbox Code Playgroud)


Anu*_*wan 4

选项1

var result = tupleList.Select(x=> { var (str,num)=x; return $"{str}{num}";})
Run Code Online (Sandbox Code Playgroud)

输出

one23 
two23 
Run Code Online (Sandbox Code Playgroud)

选项2

如果您被允许更改 tupleList 的创建,那么您可以执行以下操作。

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

选项 2 消除了选项 1 中所需的额外步骤。

  • @eddyP23:*某种*类型的“额外步骤”是不可避免的;元组解构不能与 lambda 声明结合使用。有一个[未解决的问题](https://github.com/dotnet/csharplang/issues/125),但是,它没有具体讨论 lambda 参数的声明,即使该问题得到实现,也可能继续不受支持。 (2认同)