Unpack tuple in LINQ lambda
Asked Answered
S

1

8

I have a LINQ query that uses tuples for optimization. However, I'm unable to find working syntax to unpack the tuple in the arguments, which seems surprising because C# does support unpacking tuples and other languages supporting lambdas and tuples do support unpacking.

Is there any way to leverage unpacking in the expression below instead of referencing properties of the full tuple?

            shelves
                .Select(kv => (kv.Key, kv.Value.Orders.Count))
                .Where(tuple => tuple.Count > 0)
                .OrderBy(tuple => tuple.Count)
                .Select(tuple => tuple.Key);
Straightaway answered 3/5, 2020 at 0:11 Comment(3)
please post sample input and expected outputTabitha
If you expecting to do this .Select(i => (i.Key, i.Count)).Select((key, count) => ....) - No, not implicit deconstruction into lambda parameters.Wolof
Is there a technical reason why this feature doesn't exist or could we expect to see this future?Yurikoyursa
F
12

C# supports tuple deconstruction, but it isn't possible with lambda parameters in your case.

You declared an unnamed tuple in Select and can access items using Item1, Item2, etc. properties

shelves
    .Select(kv => (kv.Key, kv.Value.Orders.Count))
    .Where(tuple => tuple.Item2 > 0)
    .OrderBy(tuple => tuple.Item2)
    .Select(tuple => tuple.Item1);

You may also switch to named tuple syntax

shelves
    .Select(kv => (Key: kv.Key, Count: kv.Value.Orders.Count))
    .Where(tuple => tuple.Count > 0)
    .OrderBy(tuple => tuple.Count)
    .Select(tuple => tuple.Key);

Or even use an anonymous type, which do not confuse you with properties names (because it uses the same name as the property being used to initialize them)

shelves
    .Select(kv => new { kv.Key, kv.Value.Orders.Count})
    .Where(x => x.Count > 0)
    .OrderBy(x => x.Count)
    .Select(x => x.Key);

As for original behavior, expected by OP, there is a proposal in C# language repository, which could be used for tracking this feature (and some extra workarounds)

Forgiven answered 3/5, 2020 at 8:3 Comment(4)
@Straightaway Does it answer your question, do you need more details or information?Forgiven
It's an answer - a fine answer - but it's not the answer we want. The answer we want is destructuring the tuple in the lambda arguments. Unfortunately, it's not the world we live in today.Cyrus
@BarryKellyThe answer confirms that what you want isn't possible, and it should still be accepted as a valid response. 😉Inauspicious
Relevant proposal github.com/dotnet/csharplang/discussions/258 in C# github repo was moved forward few weeks agoForgiven

© 2022 - 2024 — McMap. All rights reserved.