LINQ (Language Integrated Query) is a structured query syntax in .NET used to save and retrieve data from different sources.
LINQ query supports two different ways to the IEnumerable collection or IQueryable data sources.
LINQ declarative query syntax is similar to SQL, and you can create a query within your code (C# or VB).
using (var db = new CustomerDbDataContext(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=CustomerContextDB;"))
{
var customers = from customer in db.Customers
where customer.FirstName == "John"
orderby customer.LastName
select customer;
foreach (var cust in customers)
{
Console.WriteLine(cust.FirstName + ", " + cust.LastName);
}
}
LINQ query also supports method syntax which uses extension methods. The method syntax is the real way the compiler does LINQ queries.
using (var db = new CustomerDbDataContext(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=CustomerContextDB;"))
{
var customers = db.Customers
.Where(c => c.FirstName == "John")
.OrderBy(c => c.LastName);
foreach (var cust in customers)
{
Console.WriteLine(cust.FirstName + ", " + cust.LastName);
}
}
Query syntax and method syntax are semantically identical, but many people find query syntax simpler and easier to read.