Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack tuple in LINQ lambda

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);
like image 492
twinlakes Avatar asked Jun 16 '26 03:06

twinlakes


1 Answers

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)

like image 108
Pavel Anikhouski Avatar answered Jun 18 '26 16:06

Pavel Anikhouski