How to iterate over a C# tuple?

CsharpProgrammingServer Side Programming

Firstly, declare a tuple and add values −

Tuple <int, string> tuple = new Tuple<int, string>(100, "Tom");

With C#, to iterate over a tuple, you can go for individual elements −

tuple.Item1 // first item
tuple.Item2 // second item
To display the complete tuple, just use:
// display entire tuple
Console.WriteLine(tuple);

Let us see the complete code −

Example

using System;
using System.Threading;

namespace Demo {
   class Program {

      static void Main(string[] args) {

         Tuple <int, string> tuple = new Tuple<int, string>(100, "Tom");

         if (tuple.Item1 == 100) {
            Console.WriteLine(tuple.Item1);
         }
         if (tuple.Item2 == "Tom") {
            Console.WriteLine(tuple.Item2);
         }

         // display entire tuple
         Console.WriteLine(tuple);
      }
   }
}
raja
Published on 31-Aug-2018 12:48:54
Advertisements