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("値: {0}" , newList1.ElementAt(0));
Console.WriteLine("Count: {0}" , newList2.Count());
Console.WriteLine("値: {0}" , newList2.ElementAt(0));
出力:

Count: 1
値:
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("値: {0}" , newList1.ElementAt(0));
Console.WriteLine("Count: {0}" , newList2.Count());
Console.WriteLine("値: {0}" , newList2.ElementAt(0));
出力:

Count: 1
値: 0
Count: 1
値: 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