Loop a list with a Tuple C#

Viewed 7782

I have a list in C# called MyList:

List<Tuple<string, int, int>> MyList= new List<Tuple<string, int, int>>() 
        {
           Tuple.Create("Cars", 22, 3),
           Tuple.Create("Cars", 28, 5),
           Tuple.Create("Planes", 33, 6)
        };

I want to loop through the whole list in the same order as I filled it above and be able to get the values one by one for each list item, like Cars, 22, 3. How do I do that? I guess I have to use ForEach somehow.

2 Answers

You can use simple foreach loop for that, Item1, Item2 and Item3 represent an unnamed tuple items with corresponding types

foreach (var item in MyList)
{
    string name = item.Item1;
    int value = item.Item2;
    int something = item.Item3;
}

You can also switch to named tuples, which are available from C# 7. They are more readable and allow to define a custom name for tuple item and use a deconstruction

var MyList = new List<(string name, int value, int someting)>()
{
    ("Cars", 22, 3),
    ("Cars", 28, 5),
    ("Planes", 33, 6)
};

foreach (var item in MyList)
{
    var name = item.name;
    var value = item.value;
}

This is an easy to understand and simple solution that will help you.
You can use a for loop.

  • Item1 (string),
  • Item2 (int),
  • Item3 (int)

are the Tuple Items in the order and in the format that you have placed them.

And the code below is the loop.

for (int i = 0; i < MyList.Count; i++)
{
     string item1 = MyList[i].Item1;
     int item2 = MyList[i].Item2;
     int item3 = MyList[i].Item3;
}
Related