Working with four tables.
Users -> has basic user info including a userid and a departmentid (int)
Groups -> basic group info including a groupid
GroupsMembers -
How about using the coalesce operator?
userQuery = userQuery.OrderBy(u => u.Department.Name ?? string.Empty);
You can use the conditional operator to check if the department is null :
userQuery = userQuery.OrderBy(u => (u.Department != null) ? u.Department.Name : String.Empty);
For improved clarity, I created the following extension method :
public static TResult IfNotNull<TSource, TResult>(this TSource obj, Func<TSource, TResult> selector, TResult defaultValue)
{
if (obj != null)
return selector(obj);
return defaultValue;
}
It can be used as follows :
userQuery = userQuery.OrderBy(u => u.Department.IfNotNull(d => d.Name, String.Empty));