如何對 C# 元組進行迭代?


首先宣告一個元組並新增值 −

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

使用 C# 對元組進行迭代時,你可以單獨遍歷各個元素 −

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

讓我們看看完整的程式碼 −

示例

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

更新於: 2020 年 6 月 22 日

已瀏覽 2,000 次以上

開啟您的 職業生涯

完成課程以獲得認證

開始學習
廣告