- Linq Syntax and Query
- How to write Linq Query
- Query Syntax and Method Syntax
LINQ Syntax are divided into two parts.
- Query Syntax
- Method Syntax
Query Syntax
from <range variable> in <IEnumerable<T> or IQueryable<t> collection>
<standard query operators> <lambda expression>
<select or groupBy operator> <result formation
OR
from object in datasource
where condition
select object;
- from object in datasource are the initialization point.
- where is use for conditional based.
- object is used for selection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqSeries
{
public class Program
{
static void Main(string[] args)
{
//Data Source
List<string> employeeList = new List<string>()
{
"John Thomas","Lori Orona","Nick Jonas","John Mathew","Wonda Kher","Simon Ardino"
};
//LINQ Query using Query Syntax
var QuerySyntax = from obj in employeeList
where obj.Contains("John")
select obj;
//Execution
foreach (var Queryitem in QuerySyntax)
{
Console.Write(Queryitem + " ");
}
Console.ReadLine();
}
}
}
- We consider a dummy employee list - the employee list define the datasource.
- where condition is used for filter the record ( you can do it as per your requirement).
- select object is used for selection the filter list
After run the application the output be print "John Thomas" and "John Mathew" as per our filter.
Method Syntax
In this approach, the LINQ query is written by using multiple methods by combining them with a dot (.). The Syntax is given below:
DataSource.ConditionMetod().SelectionMethod()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqSeries
{
public class Program
{
static void Main(string[] args)
{
//Data Source
List<string> employeeList = new List<string>()
{
"John Thomas","Lori Orona","Nick Jonas","John Mathew","Wonda Kher","Simon Ardino"
};
//LINQ Query using Method Syntax
var MethodSyntax = employeeList.Where(emp => emp.Contains("John"));
//Execution
foreach (var methoditem in MethodSyntax)
{
Console.Write(methoditem + " ");
}
Console.ReadLine();
}
}
}
- The datasource is same as per previous example.
- We change the query syntax to method syntax with help of lambda expression.
- select object is used for selection the filter list
Benefit of use Method Syntax
- Less code with prominent result.
- More filter option with little bit enhancement.
- Lambda Expression makes writing of delegate codes much easier, simpler and readable
Summary
Post a Comment