Ngôn ngữ LINQ - Toán tử DefaultIfEmpty
Phương thức DefaultIfEmpty trong LINQ
Phương thức mở rộng DefaultIfEmpty trả về một danh sách mới với giá trị mặc định nếu danh sách đã cho rỗng.
Phương thức DefaultIfEmpty có hai phương thức quá tải. Phương thức quá tải đầu tiên không có tham số, nó trả về danh sách mới với giá trị mặc định của kiểu dữ liệu của danh sách.
Phương thức quá tải thứ hai của DefaultIfEmpty nhận tham số là giá trị mặc định sẽ được sử dụng để tạo danh sách mới khi danh sách rỗng.
Ví dụ sau minh họa phương thức DefaultIfEmpty trong LINQ:
IList<string> emptyList = new List<string>();
var newList1 = emptyList.DefaultIfEmpty();
var newList2 = emptyList.DefaultIfEmpty("None");
Console.WriteLine("Count: {0}" , newList1.Count());
Console.WriteLine("Value: {0}" , newList1.ElementAt(0));
Console.WriteLine("Count: {0}" , newList2.Count());
Console.WriteLine("Value: {0}" , newList2.ElementAt(0));
Đây là kết quả khi biên dịch và thực thi chương trình:
Count: 1
Value:
Count: 1
Value: None
Trong ví dụ trên, phương thức emptyList.DefaultIfEmpty()
trả về một danh sách kiểu string mới có một phần tử có giá trị là null vì null là giá trị mặc định của string.
Trong khi đó phương thức emptyList.DefaultIfEmpty("None")
trả về một danh sách kiểu string có một phần tử có giá trị là "None".
Ví dụ sau đây minh họa sử dụng phương thức DefaultIfEmpty trên danh sách kiểu int.
IList<int> emptyList = new List<int>();
var newList1 = emptyList.DefaultIfEmpty();
var newList2 = emptyList.DefaultIfEmpty(100);
Console.WriteLine("Count: {0}" , newList1.Count());
Console.WriteLine("Value: {0}" , newList1.ElementAt(0));
Console.WriteLine("Count: {0}" , newList2.Count());
Console.WriteLine("Value: {0}" , newList2.ElementAt(0));
Đây là kết quả khi biên dịch và thực thi chương trình:
Count: 1
Value: 0
Count: 1
Value: 100
Ví dụ sau đây minh họa phương thức DefaultIfEmpty trên danh sách có kiểu dữ liệu phức tạp.
IList<Student> emptyStudentList = new List<Student>();
var newStudentList1 = emptyStudentList.DefaultIfEmpty(new Student());
var newStudentList2 = emptyStudentList.DefaultIfEmpty(new Student()
{
StudentID = 1,
StudentName = "Default"
});
Console.WriteLine("Count: {0} ", newStudentList1.Count());
Console.WriteLine("Student ID: {0} ", newStudentList1.ElementAt(0));
Console.WriteLine("Count: {0} ", newStudentList2.Count());
Console.WriteLine("Student ID: {0} ", newStudentList2.ElementAt(0).StudentID);
Đây là kết quả khi biên dịch và thực thi chương trình:
Count: 1
Student ID: Program+Student
Count: 1
Student ID: 1