C# has one of the easy way to store multiple type of values in C# Lists, using Tuple, so in this article I have mentioned how we can create or initialize C# List with tuple or you can say how to create list of tuples in C#, with console application example.
In C# List, you can store different data types in a list in contrast to an array where all data should have the same data type, so it is always good to use List over an array.
Using Tuples in List
Let's take look at an working example, in which we will create list using tuples, so if you want replace multi-dimensional arrays, then you can list as below
var listAnimals = new List<Tuple<int, string, string>>();
listAnimals.Add(new Tuple<int, string, string>(1, "Tiger", "Carnivorous"));
listAnimals.Add(new Tuple<int, string, string>(2, "Wolf", "Carnivorous"));
So, if we consider complete example in Console application, then it can be as below
using System;
using System.Collections.Generic;
namespace UsingTupleInList
{
class Program
{
static void Main(string[] args)
{
//create list with tuple
var listAnimals = new List<Tuple<int, string, string>>();
//add elements in list
listAnimals.Add(new Tuple<int, string, string>(1, "Tiger", "Carnivorous"));
listAnimals.Add(new Tuple<int, string, string>(2, "Wolf", "Carnivorous"));
listAnimals.Add(new Tuple<int, string, string>(3, "Raccoons", "Omnivorous"));
//loop list items and print
foreach (Tuple<int, string, string> tuple in listAnimals)
{
Console.WriteLine(tuple.Item1 + " " + tuple.Item2 + " " + tuple.Item3);
}
Console.ReadLine();
}
}
}
Output
1 Tiger Carnivorous
2 Wolf Carnivorous
3 Raccoons Omnivorous
OR
You can also create List using tuples as below
using System;
using System.Collections.Generic;
namespace UsingTupleInList
{
class Program
{
static void Main(string[] args)
{
//create list with tuple
//this is changed here
var listAnimals = new List<Tuple<int, string, string>> {
Tuple.Create(1, "Tiger", "Carnivorous"),
Tuple.Create(2, "Wolf", "Carnivorous"),
};
//add elements in list
listAnimals.Add(new Tuple<int, string, string>(3, "Raccoons", "Omnivorous"));
//loop list items and print
foreach (Tuple<int, string, string> tuple in listAnimals)
{
Console.WriteLine(tuple.Item1 + " " + tuple.Item2 + " " + tuple.Item3);
}
Console.ReadLine();
}
}
}
Output is same above.
If you want to make a re-usuable solution, you can create a helper method like below
public class TupleList<T1, T2> : List<Tuple<T1, T2>>
{
public void Add( T1 item, T2 item2 )
{
Add(new Tuple<T1, T2>( item, item2 ) );
}
}
and use it as shown below, for example:
var fruitList = new TupleList<int, string>
{
{ 1, "Apple" },
{ 2, "Orange" },
{ 3, "Avacado" },
{ 4, "Banana" }
};
You may also like to read:
Return Multiple values in C# (Various ways)
Add values in C# array (Multiple ways)
Tic Tac Toe Game in C# Console application
Iterate Over Dictionary in C# (Various ways)
Compare JSON using C# and Get difference
What is console application in C#? (With Example)