Search code examples
.netlisttypesvaluetuplec#-7.3

Check individual items from a list of Valuetuple in c# 7


Please consider the following list of ValueTuple C#7

List<(double prices, int matches)> myList = new List<(double, int)>();

                    myList.Add((100, 9));  

                    myList.Add((100.50 , 12)); 

I can do Foreach var i in myList, myList.Max, myList.Average etc and it will return both types of the ValueTuple.

But, how can I check and return only the values for prices and/or matches? Can you post examples please?


Solution

  • Pattern-matching can be used to deconstruct the tuple in a for-each statement

    List<(double prices, int matches)> myList = new List<(double, int)>();
    myList.Add((100, 9));
    myList.Add((100.50, 12));
    
    foreach (var (price, match) in myList)
    {
        Console.WriteLine($"Price: {price}");
        Console.WriteLine($"Match: {match}");
    }