Csharp/C Sharp/LINQ/DefaultIfEmpty
DefaultIfEmpty Demo
<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; public class MainClass {
public static void Main() { string[] presidents = {"G", "H", "a", "H", "over", "Jack"}; string name = presidents.Where(n => n.Equals("H")).DefaultIfEmpty("Missing").First(); Console.WriteLine(name); }
}
</source>
Using DefaultIfEmpty in Where clause
<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; public class MainClass {
public static void Main() { string[] presidents = {"G", "H", "a", "H", "over", "Jack"}; string jones = presidents.Where(n => n.Equals("H")).DefaultIfEmpty().First(); if (jones != null) Console.WriteLine("H was found."); else Console.WriteLine("H was not found."); }
}
</source>
Without Using DefaultIfEmpty
<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; public class MainClass {
public static void Main() { string[] presidents = {"G", "H", "a", "H", "over", "Jack"}; string jones = presidents.Where(n => n.Equals("H")).First(); if (jones != null) Console.WriteLine("H was found"); else Console.WriteLine("H was not found"); }
}
</source>