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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With