In Python I can write
def myMethod(): #some work to find the row and col return (row, col) row, col = myMethod() mylist[row][col] # do work on this element
But in C# I find myself writing out
int[] MyMethod() { // some work to find row and col return new int[] { row, col } } int[] coords = MyMethod(); mylist[coords[0]][coords[1]] //do work on this element
The Pythonic way is obivously much cleaner. Is there a way to do this in C#?
Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable.
Python offers a very powerful tuple assignment tool that maps right hand side arguments into left hand side arguments. THis act of mapping together is known as unpacking of a tuple of values into a norml variable. WHereas in packing, we put values into a regular tuple by means of regular assignment.
Tuple Assignment (Unpacking) Unpacking or tuple assignment is the process that assigns the values on the right-hand side to the left-hand side variables. In unpacking, we basically extract the values of the tuple into a single variable.
Unpacking a Tuple Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.
For .NET 4.7 and later, you can pack and unpack a ValueTuple
:
(int, int) MyMethod() { return (row, col); } (int row, int col) = MyMethod(); // mylist[row][col]
For .NET 4.6.2 and earlier, you should install System.ValueTuple:
PM> Install-Package System.ValueTuple
There's a set of Tuple classes in .NET:
Tuple<int, int> MyMethod() { // some work to find row and col return Tuple.Create(row, col); }
But there's no compact syntax for unpacking them like in Python:
Tuple<int, int> coords = MyMethod(); mylist[coords.Item1][coords.Item2] //do work on this element
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