假设我有一个元组,比如说 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
});
我想使用 name
和 table
, 而不是 tuple.Item1
和 tuple.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/