Sunday, November 17, 2019

Few LINQ Tips that are usefull

Here are some tips in LINQ that are usefull in regular

Here are they...

  • Joins using Lambada Expressions
  • Multi select using Lambada Expression
  • Left join in Linq
  • How would you do a “not in” query with LINQ?

Joins using Lambada Expressions

Object AccountObject = _dbContext.Accounts
     .Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
     .Where(x => x.usr.EmailAddress == key1)
     .Where(x => x.usr.Hash == key2)
     .Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
     .SingleOrDefault();

multi select using lambada expression

Object AccountObject = _dbContext.Accounts
     .Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
     .Where(x => x.usr.EmailAddress == key1)
     .Where(x => x.usr.Hash == key2)
     .Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
     .SingleOrDefault();

Left Join In Linq

var query = from person in people
                join pet in pets on person equals pet.Owner into gj
                from subpet in gj.DefaultIfEmpty()
                select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };

OR

var q =
    from c in categories
    join p in products on c.Category equals p.Category into ps
    from p in ps.DefaultIfEmpty()
    select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };

How would you do a “not in” query with LINQ?

var query =  from c in dc.Customers where !(from o in dc.Orders select o.CustomerID)
             .Contains(c.CustomerID)    
             select c;

No comments:

Post a Comment