Initialize a List of Tuples in C#

Muhammad Maisam Abbas Jan 30, 2023 Mar 26, 2021
  1. Initialize a List of Tuples With the Tuple.Create() Method in C#
  2. Initialize a List of Tuples With the () Notation in C#
Initialize a List of Tuples in C#

This tutorial will discuss the methods for initializing a list of tuples in C#.

Initialize a List of Tuples With the Tuple.Create() Method in C#

The Tuple.Create(x, y) method in C# creates a new tuple with values - x and y. We can create a list of tuples and use the Tuple.Create() method while initializing the list. See the following example.

using System;
using System.Collections.Generic;

namespace list_of_tuples
{
    class Program
    {
        static void Main(string[] args)
        {
            var tupleList = new List<Tuple<int, string>>
            {
                Tuple.Create( 1, "value1" ),
                Tuple.Create( 2, "value2" ),
                Tuple.Create( 3, "value3" )
            };
            foreach(var pair in tupleList)
            {
                Console.WriteLine(pair);
            }
        }
    }
}

Output:

(1, value1)
(2, value2)
(3, value3)

In the above code, we initialized the tupleList list of tuples (int, string) with the Tuple.Create() method inside the list constructor. This approach works fine but is a bit redundant because we have to use the Tuple.Create() method for each tuple inside the list tupleList.

Initialize a List of Tuples With the () Notation in C#

The (x, y) notation in C# specifies a tuple with x and y values. Instead of the Tuple.Create() function, we can also use the () notation inside the list constructor to initialize a list of tuples. The following code example shows us how we can initialize a list of tuples with the () notation in C#.

using System;
using System.Collections.Generic;

namespace list_of_tuples
{
    class Program
    {
        static void Main(string[] args)
        {
            var tupleList = new List<(int, string)>
            {
                (1, "value1"),
                (2, "value2"),
                (3, "value3")
            };
            foreach (var pair in tupleList)
            {
                Console.WriteLine(pair);
            }
        }
    }
}

Output:

(1, value1)
(2, value2)
(3, value3)

In the above code, we initialized the tupleList list of tuples (int, string) with the (int, string) notation inside the list constructor. This approach is preferable to the previous example because it is not as redundant as the previous approach and does the same thing.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Csharp List