English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

LINQ 생성 연산자 DefaultIfEmpty

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