如果調(diào)用DefaultIfEmpty()的給定集合為空,則DefaultIfEmpty()方法將返回一個(gè)具有默認(rèn)值的新集合。
DefaultIfEmpty()的另一個(gè)重載方法接受一個(gè)值參數(shù),該參數(shù)應(yīng)替換為默認(rèn)值。
看以下示例。
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));
Count: 1 Value: Count: 1 Value: None
在上面的示例中,emptyList.DefaultIfEmpty() 返回一個(gè)新的字符串集合,其中一個(gè)元素的值為null,因?yàn)閚ull是string的默認(rèn)值。另一種方法emptyList.DefaultIfEmpty("None") 返回一個(gè)字符串集合,該字符串集合的一個(gè)元素的值為“ None”而不是null。
下面的示例演示如何在int集合上調(diào)用DefaultIfEmpty。
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));
Count: 1 Value: 0 Count: 1 Value: 100
下面的示例演示復(fù)雜類型集合的 DefaultIfEmpty() 方法。
IList<Student> emptyStudentList = new List<Student>();
var newStudentList1 = studentList.DefaultIfEmpty(new Student());
var newStudentList2 = studentList.DefaultIfEmpty(new Student(){
StudentID = 0,
StudentName = "" });
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);
Count: 1 Student ID: Count: 1 Student ID: 0