Initialize a List of Tuples in C#

  1. Initialize a List of Tuples With the Tuple.Create() Method in C
  2. Initialize a List of Tuples With the () Notation 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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp List

  • Convert an IEnumerable to a List in C#
  • Shuffle a List in C#
  • Related Article - Csharp Tuple

  • Convert Array to List in C#
  • Add String to an Array in C#