Giới thiệu
Tuple là cấu trúc dữ liệu bất biến (immutable) chứa số lượng phần tử cố định. Từ C# 7.0, bạn có thể dùng ValueTuple (tuple syntax) nhưng ví dụ này dùng Tuple.Create kiểu cũ. Để truy xuất phần tử thứ 7, sử dụng thuộc tính Item7.
Ví dụ 1: Tuple 7 phần tử (Tuple<T1..T7>)
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 có bằng Tuple2 không? = " + tuple1.Equals(tuple2));
Console.WriteLine("HashCode của Tuple1 = " + tuple1.GetHashCode());
Console.WriteLine("HashCode của Tuple2 = " + tuple2.GetHashCode());
Console.WriteLine("Tuple1 Item 1st = " + tuple1.Item1);
Console.WriteLine("Tuple2 Item 1st = " + tuple2.Item1);
Console.WriteLine("Tuple1 Item 2nd = " + tuple1.Item2);
Console.WriteLine("Tuple2 Item 2nd = " + tuple2.Item2);
Console.WriteLine("Tuple1 Item 4th = " + tuple1.Item4);
Console.WriteLine("Tuple2 Item 4th = " + tuple2.Item4);
Console.WriteLine("Tuple1 Item 5th = " + tuple1.Item5);
Console.WriteLine("Tuple2 Item 5th = " + tuple2.Item5);
Console.WriteLine("Tuple1 Item 6th = " + tuple1.Item6);
Console.WriteLine("Tuple2 Item 6th = " + tuple2.Item6);
Console.WriteLine("Tuple1 Item 7th = " + tuple1.Item7);
Console.WriteLine("Tuple2 Item 7th = " + tuple2.Item7);
}
}
Kết quả
Tuple1 có bằng Tuple2 không? = True HashCode của Tuple1 = 3231587 HashCode của Tuple2 = 3231587 Tuple1 Item 1st = 75 Tuple2 Item 1st = 75 Tuple1 Item 2nd = 200 Tuple2 Item 2nd = 200 Tuple1 Item 4th = 700 Tuple2 Item 4th = 700 Tuple1 Item 5th = 100 Tuple2 Item 5th = 100 Tuple1 Item 6th = 1200 Tuple2 Item 6th = 1200 Tuple1 Item 7th = 1500 Tuple2 Item 7th = 1500
Ví dụ 2: Tuple 8 phần tử (Tuple<T1..T8>)
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 của 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);
// Item8 cho phần tử thứ 8
Console.WriteLine("Tuple Item 8th = " + tuple.Rest.Item1); // Rest chứa phần tử thứ 8 trở đi
}
}
Kết quả
HashCode của 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
Lưu ý: Tuple cũ (System.Tuple) tối đa 8 phần tử. Phần tử thứ 8 truy xuất qua Rest.Item1. Từ C# 7.0, nên dùng ValueTuple (ví dụ: (int, int, int)) cho hiệu suất tốt hơn và hỗ trợ decompose.