【问题标题】:Linq - how to map (select) deconstructed tuples?Linq - 如何映射(选择)解构的元组?
【发布时间】:2019-10-26 00:52:55
【问题描述】:

我正在尝试实现一件非常简单的事情。我有一个 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) => ...);

【问题讨论】:

  • IEnumerable&lt;(string str, int num)&gt; ... 这也可以用作强制转换/新变量,以防您无法控制原始枚举的创建。

标签: c# linq dictionary tuples


【解决方案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 中所需的额外步骤。

【讨论】:

  • 这与我想要的很接近,但这还有一个额外的步骤:(
  • @eddyP23: some 排序的“额外步骤”是不可避免的;元组解构不能与 lambda 声明结合使用。对此有一个open issue,但它没有专门讨论 lambda 参数的声明,即使实现了该问题,也可能继续不受支持。
  • 我希望它能像 JavaScript/TypeScript 一样优雅地完成。
【解决方案2】:

你可以有命名的元组成员:

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

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 2017-04-19
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多