Suppose I have a of tuples, say List<(string, Table)>
and I want to iterate over it using a Parallel.ForEach
, using the 'named version' of the tuples' components.
The following code does that:
List<(string, Table)> list = new List<(string, Table)>();
Parallel.ForEach(list, tuple =>
{
(string name, Table table) = tuple;
// do stuff with components 'name' and 'table' here
});
I want to use name
and table
, instead of tuple.Item1
and tuple.Item2
respectively, since this makes code more readable. To make that work, I had to declare the tuple components inside the ForEach
, if I wanted to use their 'named' versions.
MY QUESTION IS:
Is there a syntax in C# which allows us to get the deconstructed version of the tuple, avoiding that declaration inside the ForEach's
body?
And if there is no such syntax, how could we achieve that with extension methods?
I mean, something like this:
List<(string, Table)> list = new List<(string, Table)>();
Parallel.ForEach(list, (string name, Table table) =>
{
// do stuff with variables 'name' and 'table' here
});
Or maybe this?
List<(string, Table)> list = new List<(string, Table)>();
Parallel.ForEach(list, (name, table) =>
{
// do stuff with variables 'name' and 'table' here
});
And, if there is a syntax for that, would it also apply to other Linq
queries?
E.g.
string[] names = parsed.Select((string name, Table table) => name).ToArray();
Instead of:
string[] names = parsed.Select(t => t.Item1).ToArray();
This would be so nice to have, especially when working with tuples containing several components, e.g. List<(int, string, int, DateTime, ...)>
. We would be able to give some context to the tuples' components inside complex Linq
queries!