简体   繁体   English

C# 7 是否允许在 linq 表达式中解构元组

[英]Does C# 7 allow to deconstruct tuples in linq expressions

I'm trying to deconstruct a tuple inside a Linq expression我正在尝试在 Linq 表达式中解构一个元组

// somewhere inside another method
var result = from word in words
             let (original, translation) = Convert(word)
             select original

Here is a signature of the method returning a tuple这是返回元组的方法的签名

(string Original, string Translation) Convert(DictionaryWord word)
{
    // implementation
}

But it's not a valid syntax.但这不是有效的语法。 I can only access tuple values without deconstruction:我只能在不解构的情况下访问元组值:

var result = from word in words
             let result = GetWord(word, mode)
             select result.Original

Is there a proper way to deconstruct it or it's not supported inside Linq expressions?是否有适当的方法来解构它,或者它在 Linq 表达式中不受支持?

It seems not.似乎没有。

There's an open issue for this on GitHub: https://github.com/dotnet/roslyn/issues/6877 GitHub 上有一个未解决的问题: https : //github.com/dotnet/roslyn/issues/6877

Edit编辑

Issue moved to dotnet/csharplang#355问题移至dotnet/csharplang#355

Deconstruction in Linq queries isn't supported in C# 7.0. C# 7.0 不支持 Linq 查询中的解构。

Only three forms of deconstruction made it into C# 7.0 (deconstruction in assignment, in "foreach" loop and in "for" loop).只有三种解构形式进入了 C# 7.0(在赋值、“foreach”循环和“for”循环中解构)。 But when the language design committee considered all the possible places that declare variables (and thus would be candidates for deconstruction) and prioritized them, the deconstruction in "let" (and possibly "from") clauses were next in line.但是,当语言设计委员会考虑了所有可能的声明变量的位置(因此将成为解构的候选者)并确定它们的优先级时,“let”(可能还有“from”)子句中的解构是下一个。

Please make sure to leave a note or a thumbs up on https://github.com/dotnet/csharplang/issues/189 if you feel this would be useful.如果您觉得这对您有用,请务必在https://github.com/dotnet/csharplang/issues/189上留言或点赞。

You can do something like this:你可以这样做:

public static (string Original, string Translation) Convert(string word)
{
    return ("Hello", "Hello translated");
}
static void Main(string[] args)
{
    List<string> words = new List<string>();
    words.Add("Hello");

    var result = from word in words
                    select Convert(word).Translation;

    Console.WriteLine("Hello, world!" + result.FirstOrDefault());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM