Search code examples
c#.netlisttuples

Loop a list with a Tuple C#


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.


Solution

  • 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;
    }