How to use extensions Method in LINQ?
LINQ also provides you extension methods those can be used to manipulate data, few extension methods are –
Where(predicate):- it will get you all instances who satisfies the predicate.
OrderBy(fieldname) :- sort the data in ascending order
OrderByDescending(fieldname) :- in descending order
Single(predicate) : – find single instance who satisfies the predicate, if found returns it, if not found throw exception, if multiple found then it will throw the exception.
SingleOrDefault(predicate) :- similar to single, if found returns it , if not found it will return default, if multiple found will throw the exception.
First([predicate]) :- will find the first insistence from the data source, if found returns it , if not found will throw exception
FirstOrDefault([predicate]):- will find the first instance from data source, if found returns it, if not found will return default.
Min(lambda) :- will help you to find the minimum from the data source for specific field.
Max() :- will help you to find the maximum from the data soruce for specific field.
Avg():- will help you to find the average for specific field from the data source.
Count():- will get yo he number of records as per condition or predicate.
sum():- will get you sum of the data for specific field.
Intersect():- will intersect two data sources and select the common from it.
Union():- will combine the multiple data source or merge the two data sources.
Take(int) :- it will select top n number of records from data source.
Skip(int): – it will skip top n number of records from data source.
Any([predicate]) :- will return a true if the instance exists otherwise will return you false.
Let us have examples of these methods, we assume following class and list exists –
class Emp
{
public Int64 EmpID { get; set; }
public string EmpName { get; set; }
public string DeptName { get; set; }
public decimal Salary { get; set; }
public string EmailID { get; set; }
public void DispEmp()
{
Console.WriteLine("Emp ID:" + this.EmpID);
Console.WriteLine("Emp Name:" + this.EmpName);
Console.WriteLine("Dept Name:" + this.DeptName);
Console.WriteLine("Salary :" + this.Salary);
Console.WriteLine("Email ID:" + this.EmailID);
}
}
List<Emp> lst = new List<Emp>();
lst.Add(new Emp() { EmpID = 121, EmpName = "Akash", DeptName = "Computer", EmailID = "Akash@hotmail.com", Salary = 12000 });
lst.Add(new Emp() { EmpID = 122, EmpName = "Amol", DeptName = "Accounts", EmailID = "Amol@hotmail.com", Salary = 15000 });
lst.Add(new Emp() { EmpID = 123, EmpName = "Sunil", DeptName = "Computer", EmailID = "Sunil@hotmail.com", Salary = 19000 });
lst.Add(new Emp() { EmpID = 124, EmpName = "Sudhir", DeptName = "Purchase", EmailID = "Sudhir@hotmail.com", Salary = 32000 });
lst.Add(new Emp() { EmpID = 125, EmpName = "Suresh", DeptName = "Computer", EmailID = "Suresh@hotmail.com", Salary = 22000 });
lst.Add(new Emp() { EmpID = 125, EmpName = "Satish", DeptName = "Purchase", EmailID = "Satish@hotmail.com", Salary = 82000 });
lst.Add(new Emp() { EmpID = 126, EmpName = "Sandeep", DeptName = "Computer", EmailID = "Sandeep@hotmail.com", Salary = 72000 });
LINQ Where(predicate) extension Method
var v = lst.Where(p => p.DeptName == "Computer" && p.Salary > 50000);
foreach (var temp in v){
temp.DispEmp();
}
Above code will find all the employees working in computer department having salary > 50000.
LINQ Orderby(lambda) method
var v = lst.OrderBy(p => p.Salary);
foreach (var temp in v)
{
temp.DispEmp();
}
Above code will display all employee records sorted in ascending order of salary.
LINQ OrderByDescending(lambda) method
var v = lst.OrderByDescending(p => p.Salary);
foreach (var temp in v)
{
temp.DispEmp();
}
Above code will display all employee records sorted in descending order of salary.
LINQ Single(predicate) Method
In single method predicate is compulsory used to find the single instance from the data source.
var v1 = lst.Single(p => p.EmpID == 123);
var v2 = lst.Single(p => p.EmpID == 4123);
var v3 = lst.Single(p => p.EmpName.StartsWith("S"));
First line of above code will get you record of sunil, since only one record of sunil exits with id 123.
Second line of above code will get exception sequence contains no element or object.
Third line of above code will get you exception sequence contains more than one element, since multiple instances found with condition.
LINQ SingleOrDefault(predicate) Method
In single method predicate is compulsory used to find the single instance from the data source.
var v = lst.SingleOrDefault(p => p.EmpID == 123);
var v = lst.SingleOrDefault(p => p.EmpID == 5698);
var v = lst.SingleOrDefault(p => p.EmpName.StartsWith("S"));
First line of above code will get you record of sunil, since only one record of sunil exits with id 123.
Second line of above code will return null since no instance or object found with condition.
Third line of above code will get you exception sequence contains more than one element, since multiple instances found with condition.
LINQ First([predicate]) Method
First Method will get you first instance if found, if not found it will throw you exception.
var v1 = lst.First();
var v2 = lst.First(p=>p.EmpID==123);
var v3 = lst.First(p=>p.EmpID==89090);
var v4 = lst.First(p=>p.EmpName.Starts("S");
First line of above code will get you record of akash, since it is first record in data source or collection.
Second line of above code will return sunil’s record since it matches with the condition.
Third line of above code will get you exception since no employee with the id passed as parameter exits.
Fourth Line of above code will get you sunil , since multiple records exits whose name starts with s and sunil is first record from it.
LINQ sum(), avg(), max(), min(), count() methods
These methods will help you to get summary of data from data source.
var m = lst.Sum(p => p.Salary);
var n= lst.Count();
var n1 =lst.Max(p=>p.Salary)
var n3=lst.Min(p=>p.Salary)
var n4=lst.Avg(p=>p.Salary)
First Line will give you total of the salary passed as parameter.
Second Line will give you count of records from lst.
Third Line will give you the maximum salary from the lst.
Fourth line will give you the minimum salary from the lst.
Fifth line will give you average of the salary from the lst.
LINQ Tak(n) and Skip(n) method
Take allow you to select top specified n number or records where as skip will help you to skip the top n number of record specified.
var v = lst.Take(3);
foreach (var temp in v)
{
temp.DispEmp();
}
Above line of code will get you top three employee records from lst i.e. akash, amol, sunil.
var v = lst.OrderByDescending(p => p.Salary).Take(2);
foreach (var temp in v)
{
temp.DispEmp();
}
above code will get you two employees getting maximum salary.
var v = lst.OrderByDescending(p => p.Salary).Skip(2).Take(2);
foreach (var temp in v)
{
temp.DispEmp();
}
above code will get you two emplyees getting maximum salary skipping first two records from the list.
LINQ Any(predicate) Method
Any method will check weather the record exits or not, if record exits it will return true otherwise it will return false.
if (lst.Any())
{
Console.WriteLine("Record Exists!");
}
else
{
Console.WriteLine("Record Not Exists!");
}
Above code will display Record Exists since the lst contains records.
if (lst.Any(p=>p.DeptName=="Computer"))
{
Console.WriteLine("Record Exists!");
}
else
{
Console.WriteLine("Record Not Exists!");
}
Above code will show you Record Exits since the record for the computer department already exits.
if (lst.Any(p=>p.DeptName"HR"))
{
Console.WriteLine("Record Exists!");
}
else
{
Console.WriteLine("Record Not Exists!");
}
Above code will show you the Record Not Exists since no employee with HR Department exits.
Combine Extension Methods with Query Syntax
You can also use the extension methods with query syntax as follows –
var v = (from t in lst
where t.DeptName == "Computer"
select t).OrderByDescending(p => p.Salary).Take(2);
foreach (var temp in v)
{
temp.DispEmp();
}
Above code will get you top 2 employees getting maximum salary from the computer department. That’s all in next article we will study joins.