C# - How to convert a list of tuples into a dictionary using the ToDictionary method

There is a built-in method in C# where you can create a dictionary from a list - it is called ToDictionary. All you need to provide to this method is how the key and value of the dictionary should be assigned. This is done using two functions (Func), which of course can be simple lambdas:

var tupleList = new List<(string Firstname, string Lastname)>
{
    ( "Peter", "Rasmussen" ),
    ( "John", "Doe" )
};

var dictionary = tupleList.ToDictionary(tuple => tuple.Firstname, tuple => tuple.Lastname);

var peterLastname = dictionary["Peter"];
var JohnLastname = dictionary["John"];

In the above example I first create a list of named tuples with two firstnames and lastnames. I then call the ToDictionary method to assign the firstname as the key of the dictionary and the lastname as the value. This gives me a dictionary where I can access the lastname easily using the firstname - as seen above.

That is it

I hope this helps you, please let me know in the comments what you think!