I found it hard to find a webpage showing a simplistic way to create named value tuples in a list. Most of the examples I could find were using a very verbose syntax, therefore I decided to write this post. As a heads up this syntax requires C# 7.
Creating named value tuples in a list
Here is a very minimalistic way to create a list of tuples with two string values:
var tupleList = new List<(string Firstname, string Lastname)>
{
( "Peter", "Rasmussen" ),
( "John", "Doe" )
};
var peterFirstname = tupleList[0].Firstname;
var peterLastname = tupleList[0].Lastname;
var johnFirstname = tupleList[1].Firstname;
var johnLastname = tupleList[1].Lastname;
The above is syntactic sugar with a cherry on the top. It uses the new named tuples from C# 7 combined with an object initialiser. In very few lines you have yourself a new list of simple values. In the above I first create the list and then access each value one after another.
Prior to C# 7
Prior to C# 7 you would have to write something like the following:
var tupleList = new List<Tuple<string, string>>
{
new Tuple<string, string>("Peter", "Rasmussen" ),
new Tuple<string, string>("John", "Doe" ),
};
Using the above your tuples would not be named and you would have to access them using Item1
, Item2
, etc. Getting the first value in the first tuple would look like the following: var peterFirstname = tupleList[0].Item1;
.
The new syntax for tuples is much more readable, simplistic and much less verbose. I hope this was the example of creating tuples in a list you were looking for! If you know a better way, please let me know in the comments! :)