serving the solutions day and night

Pages

Monday, April 22, 2013

Linq

For getting exact one instance it can be FirstOrDefault() method or SignleOrDefault() or just First() or Single().

The only difference is that methods without "OrDefault()" will throw an exception if enumeration will not satisfy their expectations, and methods with "OrDefault()" will just return null.

The dirrerence between Single and First is that Single expects exact one element in the collection and First expects at least one element.

How to get top 1 records from a query Just use FirstOrDefault() instead:

return (from a in dc.Applications
        where a.UserId == userId && a.chr_Version == version
        select a).FirstOrDefault<Application>();
SingleOrDefault() will throw an exception if there is more than one record, FirstOrDefault() will just take the first one.

Also you shouldn't have to cast to Application - your record already is of type Application.
For the first record you can try:
return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).FirstOrDefault();

For the first N use:
return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).Take(N);
Left Join SQL
select * from Employees e inner join States j on e.StateID = j.StateID left join Lookup c on (c.LookupValue = EmpTypeCode and c.LookupType ='TEMP') left join Lookup c1 on (c1.LookupValue = GovTypeCode and c1.LookupType ='PERM')

Linq
from el in db.Employees
join j in db.States on el.StateID equals j.StateID
join c1 in db.Lookup on new { etc = el.EmpTypeCode, ct1 = "TEMP" } equals new { etc = c1.LookupValue, ct1 = c1.LookupType }
into LeftJoinEmpLookup1 from c1 in LeftJoinEmpLookup1.DefaultIfEmpty()
join c2 in db.Lookup on new { gtc = el.GovTypeCode, ct2 = "PERM" } equals new { gtc = c2.LookupValue, ct2 = c2.LookupType }
into LeftJoinEmpLookup2 from c2 in LeftJoinEmpLookup2.DefaultIfEmpty()

Right Join SQL
select e.Name, d.Name from Employee e right join Department d on e.DeptID = d.ID
Linq
from dept in d
join employee in e on d.ID equals e.DeptID
into RightJoinDeptEmp from e in RightJoinDeptEmp.DefaultIfEmpty()

No comments: