İçeriğe geç

LINQ Query Examples

In this article, there are examples of grouping with more than one field, join operations, and the use of the aggregate function with Linq. The northwind database is used for examples. You can access the sample project from the link at the end of the article..

Number of Customers by Country

from customer in _context.Customers
group customer by customer.Country into g
orderby g.Count() descending
select new { 
      Ulke = g.Key,
      MusteriSayisi = g.Count() 
};

Lambda expression:

_context.Customers
.GroupBy(g => new { g.Country })
.Select(s => new { Ulke = s.Key.Country, MusteriSayisi = s.Count() })
.OrderByDescending(o => o.MusteriSayisi);

Fetch the Total Amount of Each Order with Sum() Aggregate Function

from orderDetail in _context.OrderDetails
join order in _context.Orders on orderDetail.OrderId equals order.OrderId
group orderDetail by new
{
orderDetail.OrderId
//,order.OrderDate
}
into grp
orderby grp.Key.OrderId
select new
{
SiparisNo = grp.Key.OrderId,
ToplamTutar = grp.Sum(s => (s.UnitPrice * s.Quantity))
};

Left Join | Products by Categories

from c in _context.Categories
join p in _context.Products on c.CategoryId equals p.CategoryId into ps
from p in ps.DefaultIfEmpty()
select new
{
CategoryName = c.Categoryname,
ProductName = p.ProductName
}

Lambda expression:

_context.Categories
.GroupJoin(_context.Products
, c => c.CategoryId
, p => p.CategoryId
,(x, y) => new { CategoryName = x.CategoryName, ProductName = y })
.SelectMany(x => x.ProductName.DefaultIfEmpty(), (x, y) => new { CategoryName = x.CategoryName, ProductName = y.ProductName });

Group Join

var query = (from order in _context.Orders.ToList()
join orderDetail in _context.OrderDetails.ToList()
on order.OrderId equals orderDetail.OrderId
into grp
select new
{
Siparis = order,
Detay = grp
}).Take(2).ToList();

Lambda ifadesi ile:

var lambda = _context.Orders.ToList()
.GroupJoin(_context.OrderDetails.ToList(), od => od.OrderId, o => o.OrderId, (o, od) => new { Siparis = o, Detay = od }).Select(s => s);

merterhan/linq_examples: linq query expressions (github.com)

İlk Yorumu Siz Yapın

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir