Handle Null Values in Linq Query (C#)
Avoid a null reference exception as shown in the following example:
var query1 = from c in categories where c != null join p in products on c.ID equals (p == null ? null : p.CategoryID) select new { Category = c.Name, Name = p.Name };
The where clause filters out all null elements in the categories sequence. This technique is independent of the null check in the join clause. The conditional expression with null in this example works because Products.CategoryID is of type int? which is shorthand for Nullable
In a join clause, if only one of the comparison keys is a nullable value type, you can cast the other to a nullable type in the query expression. In the following example, assume that EmployeeID is a column that contains values of type int?:
void TestMethod(Northwind db) { var query = from o in db.Orders join e in db.Employees on o.EmployeeID equals (int?)e.EmployeeID select new { o.OrderID, e.FirstName }; }Use of ternary operator as in the below example and the MobileNo = "N/A" for thenull
values:Solution 1
var user = from u in Users join uc in UserClients on u.Id equals uc.UserId into myuserwithclient from m in myuserwithclient.DefaultIfEmpty() select new { u.Id, FirstName = u.FirstName, LastName = u.LastName, UserId = m.UserId, MobileNo = (m.MobileNo == null) ? "N/A" : m.MobileNo };
Solution 2var user = from u in Users join uc in UserClients on u.Id equals uc.UserId into myuserwithclient from m in myuserwithclient.DefaultIfEmpty() select new { u.Id, FirstName = u.FirstName, LastName = u.LastName, UserId = m.UserId, MobileNo = m.MobileNo ?? "N/A" };
Reference: http://msdn.microsoft.com/en-us/library/bb882535.aspx
No comments:
Post a Comment
Comments Welcome