Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop a list with a Tuple C#

Tags:

c#

.net

list

tuples

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.

like image 419
KGB91 Avatar asked Jun 17 '26 03:06

KGB91


1 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;
}
like image 73
Pavel Anikhouski Avatar answered Jun 18 '26 15:06

Pavel Anikhouski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!