如何在 C# 中建立 3 元組或三元組?
Tuple<T1, T2, T3> 類表示 3 元組,稱為三元組。元組是一種具有元素序列的資料結構。
它用於 −
- 更輕鬆地訪問資料集。
- 更輕鬆地操作資料集。
- 表示單個的資料集。
- 從方法返回多個值
- 將多個值傳遞給方法
示例
現在讓我們看一個示例,在 C# 中實現 3 元組 −
using System; public class Demo { public static void Main(string[] args) { Tuple<int,string,string> tuple = new Tuple<int,string,string>(35, "steve", "katie"); Console.WriteLine("Value (Item1)= " + tuple.Item1); Console.WriteLine("Value (Item2)= " + tuple.Item2); Console.WriteLine("Value (Item3)= " + tuple.Item3); if (tuple.Item1 == 35) { Console.WriteLine("Exists: Tuple Value = " +tuple.Item1); } if (tuple.Item2 == "jack") { Console.WriteLine("Exists: Tuple Value = " +tuple.Item2); } if (tuple.Item3 == "katie") { Console.WriteLine("Exists: Tuple Value = " +tuple.Item3); } } }
輸出
這將生成以下輸出 −
Value (Item1)= 35 Value (Item2)= steve Value (Item3)= katie Exists: Tuple Value = 35 Exists: Tuple Value = katie
示例
現在讓我們看另一個示例,在 C# 中實現 3 元組 −
using System; public class Demo { public static void Main(string[] args) { Tuple<string,string,string> tuple = new Tuple<string,string,string>("nathan", "steve", "katie"); Console.WriteLine("Value (Item1)= " + tuple.Item1); Console.WriteLine("Value (Item2)= " + tuple.Item2); Console.WriteLine("Value (Item3)= " + tuple.Item3); if (tuple.Item1 == "nathan") { Console.WriteLine("Exists: Tuple Value = " +tuple.Item1); } if (tuple.Item2 == "jack") { Console.WriteLine("Exists: Tuple Value = " +tuple.Item2); } if (tuple.Item3 == "katie") { Console.WriteLine("Exists: Tuple Value = " +tuple.Item3); } } }
輸出
這將生成以下輸出 −
Value (Item1)= nathan Value (Item2)= steve Value (Item3)= katie Exists: Tuple Value = nathan Exists: Tuple Value = katie
廣告