In this post I am going to discuss about Default extension method(s) which are use full when we query the data form the collection,array or performing operation while code using linq to sql.
In .net framework there are number of extension methods which allows perform function on the the collection. But problem arise when we don’t know the collection or array empty or there is no element after we apply filter.
Methods like .First<t>(),.Last<t>(),.Single<t>() always throws exception InvalidOperationException when object collection is empty or if there is no element available after applying filter condition.
List<int> lstInt = new List<int>(new int[] {15,11,20,30}); var data = lstInt.Single(i => i < 10);
Default Methods
To avoid the exception .net framework has default methods like .FirstOrDefault<t>(),.LastOrDefault<t>(),.SingleOrDefault<t>(), which return the default value if there is no element in the collection or array is empty.
List<int> lstInt = new List<int>(new int[] {15,11,20,30}); var data = lstInt.SingleOrDefualt(i => i < 10); if (data == 0) { Console.WriteLine("No element found"); }
What if I have collection which is empty and apply the default method, it will return Null value.
class Employee { public string Name { get; set; } public int Age { get; set; } public static void GetEmployee() { List<Employee> lstEmp = new List<Employee>(); var lst = lstEmp.SingleOrDefault(); if (lst == null) Console.WriteLine("list is empty"); } }
But I want to display the default value if collection is empty. So for the solution .net Framework provided method DefualtIfEmpty() which allow to do so.
class Employee { public string Name { get; set; } public int Age { get; set; } public static void GetEmployee() { List<Employee> lstEmp = new List<Employee(); Employee defualtEmp = new Employee() { Name = "defualt", Age = 0 }; var lst = lstEmp.DefaultIfEmpty(defualtEmp).Single(); Console.WriteLine("Employee :" + lst.Name); } }
The above method is also help full when I am apply filter on the collection and collection is empty.
public static void GetEmployee() { List<Employee> lstEmp = new List<Employee>{ new Employee(){Name = "Pranay", Age =25 }, new Employee(){Name = "Krunal", Age = 26}, new Employee(){Name = "Hanika", Age = 26} }; Employee defualtEmp = new Employee() { Name = "defualt", Age = 0 }; var emp = lstEmp.Where(e=>e.Age<20).DefaultIfEmpty(defualtEmp); foreach(Employee e in emp) Console.WriteLine("Fond Employee: " + e.Name); }
The above code is the example but it’s very help full when I am binding collection with the list controls