c# - 如何在 Linq 查询中获取 'named' 元组组件?

标签 c# linq lambda tuples c#-7.3

假设我有一个元组,比如说 List<(string, Table)>我想使用 Parallel.ForEach 对其进行迭代,使用元组组件的“命名版本”。

下面的代码就是这样做的:

List<(string, Table)> list = new List<(string, Table)>();
Parallel.ForEach(list, tuple => 
{
    (string name, Table table) = tuple;

    // do stuff with components 'name' and 'table' here
});

我想使用 nametable , 而不是 tuple.Item1tuple.Item2分别,因为这使代码更具可读性。为了让它工作,我必须在 ForEach 中声明元组组件。 ,如果我想使用他们的“命名”版本。


我的问题是:

C# 中是否有一种语法允许我们获得元组的解构版本,避免在 ForEach's 中声明? body ?

如果没有这样的语法,我们怎么能用扩展方法来实现呢?


我的意思是,像这样:

List<(string, Table)> list = new List<(string, Table)>();
Parallel.ForEach(list, (string name, Table table) => 
{
    // do stuff with variables 'name' and 'table' here
});

或者可能是这个?

List<(string, Table)> list = new List<(string, Table)>();
Parallel.ForEach(list, (name, table) => 
{
    // do stuff with variables 'name' and 'table' here
});


而且,如果有语法,它是否也适用于其他 Linq有疑问吗?

例如

string[] names = parsed.Select((string name, Table table) => name).ToArray();

代替:

string[] names = parsed.Select(t => t.Item1).ToArray();


这将是非常好的,特别是在处理包含多个组件的元组时,例如List<(int, string, int, DateTime, ...)> .我们将能够为复杂 Linq 中的元组组件提供一些上下文查询!

最佳答案

How to get 'named' tuple components inside Linq queries?

最简单的解决办法是给你的元素起一个名字,就像这样

List<(string Name, Table Table)> list = new List<(string, Table)>();
// or simply
var list = new List<(string Name, Table Table)>();

Parallel.ForEach(list, t => 
{
    // do something with t.Name, t.Table
    var name = t.Name;
    var table = t.Table;
});

Is there a syntax in C# which allows us to get the deconstructed version .. inside the ForEach

Afaik 编号。

关于c# - 如何在 Linq 查询中获取 'named' 元组组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52477753/

相关文章:

c# - 为什么 LINQ 不允许我对我的数据点之一进行排序?

vb.net - list<Of T> 上的多种排序

python - 在 addConstraint 中使用变量会产生错误的答案,但不使用变量则可以正常工作

java - sonarLint:使这个匿名内部类成为 lambda

c# - Lambda 表达式仅从集合中选择某些项目

c# - 考虑线程和并发请求生成自动编号

C# 计算器异常

c# - 绑定(bind)到其他元素(高度减去 5px)

c# - 让程序确保它有 3 个自己的实例一直在运行?

linq - NHibernate 3 LINQ 内连接问题与三个跳转 : NotSupportedException