Giới thiệu
Tuple cung cấp thuộc tính Item5 để truy cập phần tử thứ 5 (1-based). Tương tự Item1 đến Item7 và Rest cho phần tử thứ 8 trở đi.
Ví dụ 1: So sánh Item5 của hai tuple giống nhau
using System;
public class Demo
{
public static void Main(string[] args)
{
var tuple1 = Tuple.Create(75, 200, 500, 700, 100, 1200, 1500);
var tuple2 = Tuple.Create(75, 200, 500, 700, 100, 1200, 1500);
Console.WriteLine("Tuple1 bằng Tuple2? = " + tuple1.Equals(tuple2));
Console.WriteLine("HashCode Tuple1 = " + tuple1.GetHashCode());
Console.WriteLine("HashCode Tuple2 = " + tuple2.GetHashCode());
Console.WriteLine("Tuple1 Item 5th = " + tuple1.Item5);
Console.WriteLine("Tuple2 Item 5th = " + tuple2.Item5);
}
}
Kết quả
Tuple1 bằng Tuple2? = True
HashCode Tuple1 = 3231587
HashCode Tuple2 = 3231587
Tuple1 Item 5th = 100
Tuple2 Item 5th = 100
Ví dụ 2: Tuple 8 phần tử, truy cập Item1-Item7
using System;
public class Demo
{
public static void Main(string[] args)
{
var tuple = Tuple.Create(1200, 1500, 2200, 2700, 3100, 3500, 4500, 5500);
Console.WriteLine("HashCode Tuple = " + tuple.GetHashCode());
Console.WriteLine("Tuple Item 1st = " + tuple.Item1);
Console.WriteLine("Tuple Item 2nd = " + tuple.Item2);
Console.WriteLine("Tuple Item 3rd = " + tuple.Item3);
Console.WriteLine("Tuple Item 4th = " + tuple.Item4);
Console.WriteLine("Tuple Item 5th = " + tuple.Item5);
Console.WriteLine("Tuple Item 6th = " + tuple.Item6);
Console.WriteLine("Tuple Item 7th = " + tuple.Item7);
// Phần tử 8: tuple.Rest.Item1
}
}
Kết quả
HashCode Tuple = 49989024
Tuple Item 1st = 1200
Tuple Item 2nd = 1500
Tuple Item 3rd = 2200
Tuple Item 4th = 2700
Tuple Item 5th = 3100
Tuple Item 6th = 3500
Tuple Item 7th = 4500
Mẹo
- Tuple là immutable; muốn thay đổi giá trị phải tạo tuple mới.
- Dùng
ValueTuple(struct) từ C# 7 cho hiệu suất tốt hơn và cú pháp gọn:(int, int, int, int, int) t = (1,2,3,4,5); t.Item5.