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); } }
Author: coder
Without Using DefaultIfEmpty
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"); } }
Using DefaultIfEmpty in Where clause
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."); } }
Deferred Query Execution: shows how query execution is deferred until the query is enumerated at a foreach statement.
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class MainClass { public static void Main() { int[] numbers = new int[] { 5, 4, 1, 3, 9 }; int i = 0; var q = from n in numbers select ++i; foreach (var v in q) { Console.WriteLine("v = {0}, i = {1}", v, i); } } }
How queries can be executed immediately with operators such as ToList().
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class MainClass { public static void Main() { int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int i = 0; var q = ( from n in numbers select ++i) .ToList(); // The local variable i has already been fully // incremented before we iterate the results: foreach (var v in q) { Console.WriteLine("v = {0}, i = {1}", v, i); } } }
The aggregation operators return a scalar value
using System; using System.Collections.Generic; using System.Linq; public class MainClass { public static void Main() { int[] numbers = { 10, 9, 8, 7, 6 }; int count = numbers.Count(); int min = numbers.Min(); } }
Contains with IEqualityComparer
using System; using System.Linq; using System.Collections; using System.Collections.Generic; public class MyStringifiedNumberComparer : IEqualityComparer<string> { public bool Equals(string x, string y) { return (Int32.Parse(x) == Int32.Parse(y)); } public int GetHashCode(string obj) { return Int32.Parse(obj).ToString().GetHashCode(); } } public class MainClass { public static void Main() { string[] stringifiedNums = {"001", "49", "017", "0080", "00027", "2" }; bool contains = stringifiedNums.Contains("2",new MyStringifiedNumberComparer()); Console.WriteLine(contains); } }