C# - How to make a list of tuples with named values

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.

Selecting a class as a named tuple

Another scenario may be that you want to select a list of classes as a list of named tuples. If we have the following class:

class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

and we create a list of objects of that class:
var list = new List<Person>
{
    new Person { Firstname = "Peter", Lastname = "Rasmussen" },
    new Person { Firstname = "John", Lastname = "Doe" },
};

We can then use select to get the list of classes as a list of named tuples:
var tupleListFromClass = list.Select(x => new { 
    Firstname = x.Firstname,
    Lastname = x.Lastname
}).ToList();

In the above we use the same names for the tuple named values and the class properties, that might be confusing and seem redundant - but it is just an example.

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! :)