Does C# 7 allow to deconstruct tuples in linq expressions
Asked Answered
K

3

33

I'm trying to deconstruct a tuple inside a Linq expression

// 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 = Convert(word)
             select result.Original

Is there a proper way to deconstruct it or is it not supported inside Linq expressions?

Kruse answered 30/11, 2016 at 22:45 Comment(1)
LINQ integration wasn't very well thought out with C# 7, unfortunately.Stob
W
28

It seems not.

There's an open issue for this on GitHub: https://github.com/dotnet/roslyn/issues/6877

Edit

Issue moved to dotnet/csharplang#355

Whitsunday answered 30/11, 2016 at 22:54 Comment(3)
Indeed, it does not compile with the current Roslyn master.Magniloquent
Thank you. It's sad that it's still on a backlogKruse
In 2022, we cannot use from (x, y) in points or let (x, y) = point.Schizophyceous
C
9

Deconstruction in Linq queries isn't supported in C# 7.0.

Only three forms of deconstruction made it into C# 7.0 (deconstruction in assignment, in "foreach" loop and in "for" loop). 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.

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.

Comminate answered 12/3, 2017 at 3:49 Comment(0)
H
2

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());
}
Hexarchy answered 30/9, 2020 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.