LINQ To Entity Framework Tutorial – Part II

In this post, I am going to explain below operations in LINQ.
  1. Sorting
  2. Group By
  3. Left Join
1) Sorting: Ascending:
Employee[] AllEmployees = (from E in NorthwindEntity.Employees
orderby E.FirstName ascending
select E).ToArray();

Descending:
Employee[] AllEmployees = (from E in NorthwindEntity.Employees
orderby E.FirstName descending
select E).ToArray();

2) Group By:
    var AllEmployee = from E in NorthwindEntity.Employees
    group E by E.LastName into G
    select new { LastName = G.Key, Group = G };
    
    foreach (var employees in AllEmployee)
    {
    // employees.Group is the current group 
    // Here you will find each group ( using employees.Group ) for employees.LastName
    
    foreach (var employee in employees.Group)
    {
    // Here you will find each employee in particular group
    // You can access each property of Employee object here.
    }
    }
3) Left Join:
    var allProductsWithCategory = from p in NorthwindEntity.Products
    let c = (from c in NorthwindEntity.Categories
    where c.CategoryID == p.CategoryID
    select c).FirstOrDefault()
    select new { Productname = p.ProductName, CategoryName = c.CategoryName };
    
    foreach (var item in allProductsWithCategory)
    {
    
    // You will find product's name and category row by row here...
    // item.Productname
    // item.CategoryName;
    
    }
That’s all for today’s post, In my next post I will try to upload demo project to understand LINQ more.
For next post I have two topics in my mind:
  1. Using lambda expressions
  2. Bulk insert / update / delete operations

Comments

Popular posts from this blog

Lambda Expressions In Entity Framework

LINQ To Entity Framework Tutorial

Select Columns From Multiple Tables Using LINQ