Linq OrderBy breaks with navigation property being null

*爱你&永不变心* 提交于 2019-12-03 02:34:33

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));

How about using the coalesce operator?

userQuery = userQuery.OrderBy(u => u.Department.Name ?? string.Empty);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!