2

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?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Roblogic
  • 107
  • 3
  • 8

3 Answers3

3

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}");
}
Jonas
  • 737
  • 1
  • 8
  • 20
1

You can just use the Select(x => x.prices)

static void Main(string[] args)
{
    List<(double prices, int matches)> myList = new List<(double, int)>();
    myList.Add((100, 9));
    myList.Add((100.50, 12));

    var prices = myList.Select(x => x.prices);
    var matches = myList.Select(x => x.matches);

    Console.WriteLine("prices:");
    foreach (var item in prices)
        Console.WriteLine(item);

    Console.WriteLine("\nmatches:");
    foreach (var item in matches)
        Console.WriteLine(item);

    Console.Read();
}

Output:

prices:
100
100.5

matches:
9
12
L_J
  • 2,351
  • 10
  • 23
  • 28
  • 1
    Thanks very much!! Simple and powerful!! – Roblogic Jul 14 '18 at 12:43
  • And how can this be done if instead of returning "prices" and "matches" in a IEnumerable, these are returned inside a new List? Is that possible to do it direct or it needs the Select to return the values as IEnumerable and then add them to a List ? – Roblogic Jul 15 '18 at 00:30
0

I prefer this approach:

var _someCollection = new List<(int Id, string Name)> { (123, "abc") };
...
_someCollection.ForEach(_ => {
   _.Id = 1;
   _.Name = "a";
});

In this case you do not need to redefine names as needed in simple foreach statement, which can lead to bugs and harder to debug code if renamed differently.

donatasj87
  • 760
  • 9
  • 23