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

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

假设我有一个元组,比如 List<(string, Table)>,我想使用元组组件的 'named version' 使用 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,因为这样可以提高代码的可读性。为了让它工作,如果我想使用它们的 'named' 版本,我必须在 ForEach 中声明元组组件。


我的问题是:

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

如果没有这样的语法,我们如何通过扩展方法实现呢?


我的意思是,像这样:

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 编号

我觉得你想要这样的东西?

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

你必须使用 : 而不是 =

var k = executeResultSet.Select(s => new
{
    IDUser = (int) s["IDUser"],
    SourceCode = s["SourceCode"],
    SourceSystem = s["SourceSystem"]
}).ToList();

var k = executeResultSet.Select(s => 
(
    IDUser: (int) s["IDUser"],
    SourceCode: s["SourceCode"],
    SourceSystem: s["SourceSystem"]
)).ToList();

不完全是您想要的,但这是 Christoph 回答的替代方法:

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