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

标签 c# linq dictionary tuples

我正在尝试实现一个非常简单的事情。我有一个可枚举的元组,我想同时映射和解构它们(因为使用 .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) => ...);

最佳答案

选项 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 中所需的额外步骤。

关于c# - Linq - 如何映射(选择)解构的元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56546425/

相关文章:

c# - 单个绑定(bind)的多个验证规则

c# - Lambda 表达式,从 Python 到 C#

c# - 如何选择当前选中项的DisplayMember或DisplayValue?

algorithm - F# FSharpMap 与字典性能

c# - 未找到 Jenkins NUnit 报告文件

c# - 我应该如何在 Vector3 结构中实现 .Equals() ?

c# - 我可以比较两个字典的键吗?

c# - Linq 查询 - List<T> 上的 "Where",其中反射(reflect)的属性包含文本/值

c# - 用字符串中的单个字符修剪重复字符

c# - xml c# 使用 Linq 添加元素到 Xml