如果调用DefaultIfEmpty()的给定集合为空,则DefaultIfEmpty()方法将返回一个具有默认值的新集合。
DefaultIfEmpty()的另一个重载方法接受一个值参数,该参数应替换为默认值。
看以下示例。
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() 返回一个新的字符串集合,其中一个元素的值为null,因为null是string的默认值。另一种方法emptyList.DefaultIfEmpty("None") 返回一个字符串集合,该字符串集合的一个元素的值为“ None”而不是null。
下面的示例演示如何在int集合上调用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
下面的示例演示复杂类型集合的 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