T-Sql coalesce usage:

select c.ContactName, EmpID= coalesce(o.EmployeeID,-1)
from Customers c
left outer join Orders o on o.CustomerID = c.CustomerID

Same Query with Linq ?? operator:

DataClassesDataContext db = new DataClassesDataContext();
var Cust = from c in db.Customers
join o in db.Orders on c.CustomerID equals o.CustomerID into g
from o in g.DefaultIfEmpty()
select new {c.ContactName, EmpID = o.EmployeeID ?? -1 };

4 Comments»

  1. how should i use ?? operator in the following coding.

    int iNewOitem = dc.tOrderDetails.Max(u => u.OrderItemId)+ 1;

    Objective : if the database value is null ” dc.tOrderDetails.Max(u => u.OrderItemId) ” should return the value “0″ else it may return the exact maximum value .

    how is it possible ? hope u can understand ?

    regards,
    Durai karthik

    Comment by Duraikarthik — April 16, 2008@ 4:35 pm

  2. If you only want to check value of u.OrderItemId, you should use like;

    int iNewOitem = dc.tOrderDetails.Max(u => u.OrderItemId ?? 0)+ 1;

    Comment by admin — April 16, 2008@ 5:47 pm

  3. It gives the following error after i used this coding

    int iNewOitem = dc.tOrderDetails.Max(u => u.OrderItemId ?? 0) + 1;

    Operator ‘??’ cannot be applied to operands of type ‘int’ and ‘int’

    Kindly give me a solution.

    Comment by Durai karthik — April 16, 2008@ 6:41 pm

  4. try this one,

    int iNewOitem = dc.tOrderDetails.Max(u => (int?)u.OrderItemId ?? 0) + 1;

    Comment by admin — April 17, 2008@ 12:40 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by Mucitsoft