HOWTO · Csharp
在 C# 中初始化元組列表
可使用兩種主要方法初始化 C# 中的元組列表,即 Tuple.Create()方法和()表示法。
本教程將討論在 C# 中初始化元組列表的方法。
在 C# 中使用 Tuple.Create() 方法初始化元組列表
C# 中的 Tuple.Create(x, y) 方法建立一個具有值 x 和 y 的新元組。我們可以建立一個元組列表,並在初始化列表時使用 Tuple.Create() 方法。請參見以下示例。
using System;
using System.Collections.Generic;
namespace list_of_tuples {
class Program {
static void Main(string[] args) {
var tupleList =
new List<Tuple<int, string>> { Tuple.Create(1, "value1"), Tuple.Create(2, "value2"),
Tuple.Create(3, "value3") };
foreach (var pair in tupleList) {
Console.WriteLine(pair);
}
}
}
}
輸出:
(1, value1)
(2, value2)
(3, value3)
在上面的程式碼中,我們使用列表建構函式中的 Tuple.Create() 方法初始化了 (int, string) 的 tupleList 列表。這種方法很好用,但是有點多餘,因為我們必須對 tupleList 列表中的每個元組使用 Tuple.Create() 方法。
在 C# 中使用 () 表示法初始化元組列表
C# 中的 (x, y) 表示法指定具有 x 和 y 值的元組。除了 Tuple.Create() 函式外,我們還可以使用列表建構函式中的 () 表示法來初始化元組列表。下面的程式碼示例向我們展示瞭如何使用 C# 中的 () 表示法初始化元組列表。
using System;
using System.Collections.Generic;
namespace list_of_tuples {
class Program {
static void Main(string[] args) {
var tupleList = new List<(int, string)> { (1, "value1"), (2, "value2"), (3, "value3") };
foreach (var pair in tupleList) {
Console.WriteLine(pair);
}
}
}
}
輸出:
(1, value1)
(2, value2)
(3, value3)
在上面的程式碼中,我們使用列表建構函式中的 (int, string) 標記初始化了元組 (int, string) 的 tupleList 列表。此方法比前面的示例更好,因為它不像前面的方法那樣多餘,並且執行相同的操作。