LINQ (Language Integrated Query) is a powerful feature in .NET that allows querying data using a syntax similar to SQL, directly in C# or other .NET languages. LINQ simplifies the process of working with data in databases, collections, XML, and other sources.
Let’s explore LINQ queries with step-by-step examples:
// Example: Get all customers
using (var context = new ApplicationDbContext())
{
var customers = context.Customers.ToList();
}
This query retrieves all customers from the Customers
table.
// Example: Get customers from a specific city
using (var context = new ApplicationDbContext())
{
var customersInCity = context.Customers
.Where(c => c.City == "New York")
.ToList();
}
The Where
method filters customers who are from "New York."
// Example: Get customer names and cities
using (var context = new ApplicationDbContext())
{
var customerDetails = context.Customers
.Select(c => new { c.Name, c.City })
.ToList();
}
The Select
method is used to project specific columns (Name and City) into an anonymous
type.
// Example: Get orders with customer names
using (var context = new ApplicationDbContext())
{
var ordersWithCustomerNames = context.Orders
.Join(context.Customers,
order => order.CustomerId,
customer => customer.Id,
(order, customer) => new { order.Id, customer.Name, order.Total })
.ToList();
}
The Join
method combines data from the Orders
and Customers
tables using the CustomerId
key.
// Example: Group orders by customer
using (var context = new ApplicationDbContext())
{
var ordersByCustomer = context.Orders
.GroupBy(o => o.CustomerId)
.Select(group => new
{
CustomerId = group.Key,
TotalOrders = group.Count(),
TotalAmount = group.Sum(o => o.Total)
})
.ToList();
}
This query groups orders by CustomerId
and calculates the number of orders and total
amount for each customer.