Element Operators in LINQ C#
Element operators return single value or a default value from input sequence.In this blog I am demonstrating following linq element operators.
- first
- firstordefault
- last
- lastordefault
- single
- singleordefault
- elementat
- elementatordefault
- defaultifempty
1. First
It returns first from a list, array and collection etc.
Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQExample { class Program { static void Main(string[] args) { string[] firstlist = { "item1", "item2", "item3", "item4", "item2", "item3", "item10" }; //Lets use intersect function string itemname = firstlist.First(); Console.WriteLine("First Item is = " + itemname); Console.ReadLine(); } } }
Note : We can also get first elements using predicate function or lambda expression, but remember whenever any elements does not find as per lambda express , first operator throws an exception(“System.InvalidOperationException : Sequence contains no matching element.” ) .In this condition we will use firstordefault operator.
Now we will see that how we can get element using lambda expression.
Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQExample { class Program { static void Main(string[] args) { Employee[] Employees = { new Employee { Name = "Ramesh", salary = 500 , departmentname="IT"}, new Employee { Name = "Suresh", salary = 100 , departmentname="Sales"}, new Employee { Name = "Yogesh", salary = 150 , departmentname="Marketting"}, new Employee { Name = "Harish", salary = 500 , departmentname="HR"}, new Employee { Name = "Giraj", salary = 1000 , departmentname="HR"}, new Employee { Name = "Vijay", salary = 100, departmentname="IT" } }; Employee emp = Employees.First(x => x.departmentname == "HR"); Console.WriteLine("First Employee of HR department is "+emp.Name); Console.ReadLine(); } public class Employee { public string Name; public int salary; public string departmentname; } } }
OutPut
FirstOrDefault element operator in linq C#
It works same as first element operator but the difference between first and firstordefault is that firstordefault returns default value of element rather than throw exception which is thrown by first element operator.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQExample { class Program { static void Main(string[] args) { Employee[] Employees = { new Employee { Name = "Ramesh", salary = 500 , departmentname="IT"}, new Employee { Name = "Suresh", salary = 100 , departmentname="Sales"}, new Employee { Name = "Yogesh", salary = 150 , departmentname="Marketting"}, new Employee { Name = "Harish", salary = 500 , departmentname="HR"}, new Employee { Name = "Giraj", salary = 1000 , departmentname="HR"}, new Employee { Name = "Vijay", salary = 100, departmentname="IT" } }; //This will return Harish // Employee emp = Employees.FirstOrDefault(x => x.departmentname == "HR"); //As we know salesmanagement department does not exists so It will retern default value of departmentname which by default null Employee emp = Employees.FirstOrDefault(x => x.departmentname == "SalesManagement"); if (emp != null) { Console.WriteLine("First Employee of HR department is "+emp.Name.ToString()); } else { //This message will be shown on console Console.WriteLine("SalesManagement Department Employee Does Not exists"); } Console.ReadLine(); } public class Employee { public string Name; public int salary; public string departmentname; } } }
Last and LastorDefault in LINQ C#
3. Last: return last element, if predicate is defined and no elements are find as per prdicate condition then it will throw exception.
4. LastorDefault: It works same as Last operator but it will return input list element’s default value rather than exception.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQExample { class Program { static void Main(string[] args) { Employee[] Employees = { new Employee { Name = "Ramesh", salary = 500 , departmentname="IT"}, new Employee { Name = "Suresh", salary = 100 , departmentname="Sales"}, new Employee { Name = "Yogesh", salary = 150 , departmentname="Marketting"}, new Employee { Name = "Harish", salary = 500 , departmentname="HR"}, new Employee { Name = "Giraj", salary = 1000 , departmentname="HR"}, new Employee { Name = "Vijay", salary = 100, departmentname="IT" } }; Employee emp = Employees.Last(x => x.departmentname == "HR"); Console.WriteLine("Last employee of HR department is " + emp.Name); Employee emp1 = Employees.LastOrDefault(x => x.departmentname == "SalesManagement"); if (emp1 != null) { Console.WriteLine("First Employee of HR department is "+emp1.Name.ToString()); } else { //This message will be shown on console Console.WriteLine("SalesManagement Department Employee Does Not exists"); } Console.ReadLine(); } public class Employee { public string Name; public int salary; public string departmentname; } } }
5. Single
The Single query operator returns the only element in the input sequence. If the input sequence contains more than one element, an exception is thrown: ”System.InvalidOperationException : Sequence contains more than one element.” If the input sequence contains zero elements, an exception will also be thrown: “System.InvalidOperationException : Sequence contains no elements.”
6. SingleorDefault:
It is very much similar as Single but the only difference is If the predicate version is being used and no matching elements are found, the default value is again returned, rather than an exception
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQExample { class Program { static void Main(string[] args) { Employee[] Employees = { new Employee { Name = "Suresh", salary = 1000 , departmentname="Sales"}, new Employee { Name = "Yogesh", salary = 150 , departmentname="Marketting"}, new Employee { Name = "Harish", salary = 5000 , departmentname="HR"}, new Employee { Name = "Vijay", salary = 100, departmentname="IT" } }; //if take one employee object in employees arrays then it works fine //but if there are multiple employee object in Employees array then it will throw exception //Employee emp = Employees.Single(); //Pass Predicate Employee emp = Employees.Single(x => x.departmentname == "HR"); Console.WriteLine("Single employee of HR department is " + emp.Name); Employee emp1 = Employees.SingleOrDefault(x => x.departmentname == "SalesManagement"); if (emp1 != null) { Console.WriteLine("Single Employee of HR department is " + emp1.Name.ToString()); } else { //This message will be shown on console Console.WriteLine("SalesManagement Department Employee Does Not exists"); } Console.ReadLine(); } public class Employee { public string Name; public int salary; public string departmentname; } } }
ElementAt and ElementAtDefault in LINQ C#
6. The ElementAt query operator returns the element that exists at the specified position in the input sequence.
Notice that the value passed to ElementAt is a zero-based index; for example, to select the first element, the value would be 0.
If the value passed to ElementAt tries to select an element that is greater than the number of elements in the input sequence, an exception will be thrown: “Index was out of range. Must be non-negative and less than the size of the collection.”
7. The ElementAtOrDefault query operator works in a similar way to ElementAt, but rather than throw an exception if the value passed to it exceeds the size of the input sequence, it will return the default value for the input type.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQExample { class Program { static void Main(string[] args) { Employee[] Employees = { new Employee { Name = "Suresh", salary = 1000 , departmentname="Sales"}, new Employee { Name = "Yogesh", salary = 150 , departmentname="Marketting"}, new Employee { Name = "Harish", salary = 5000 , departmentname="HR"}, new Employee { Name = "Vijay", salary = 100, departmentname="IT" } }; Employee emp = Employees.ElementAt(2); Console.WriteLine("Elemenet at Position 2 is "+emp.Name); Employee emp1 = Employees.ElementAtOrDefault(5); if (emp1 != null) { Console.WriteLine(" Employee at position 5 is " + emp1.Name); } else { //This message will be shown on console Console.WriteLine(" Employee Does Not exists at position 5"); } Console.ReadLine(); } public class Employee { public string Name; public int salary; public string departmentname; } } }
8. DefaultIfEmpty
The DefaultIfEmpty query operator takes an input sequence and does one of two things. If the input sequence contains at least one element, then the input sequence is returned without any changes. If, however, the input sequence contains zero elements, the output sequence returned will not be empty; it will contain a single element with a default value.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQExample { class Program { static void Main(string[] args) { Employee[] Employees = { new Employee { Name = "Suresh", salary = 1000 , departmentname="Sales"}, new Employee { Name = "Yogesh", salary = 150 , departmentname="Marketting"}, new Employee { Name = "Harish", salary = 5000 , departmentname="HR"}, new Employee { Name = "Vijay", salary = 100, departmentname="IT" } }; IEnumerable<Employee> emp = Employees.DefaultIfEmpty(); //Below Code will be executed fine foreach(Employee em in emp ) { Console.WriteLine("Elements are " + em.Name); } Dept[] dept = { }; IEnumerable<Dept> dept1 = dept.DefaultIfEmpty(); if (dept1 != null) { Console.WriteLine(" Department are exits"); } else { //This message will be shown on console Console.WriteLine(" Departments are not exists"); } Console.ReadLine(); } public class Employee { public string Name; public int salary; public string departmentname; } public class Dept { public string Name; } } }