如果LINQ中的列为空,如何忽略"where"和"order by"条件 [英] How to ignore 'where' and 'order by' condition if the column is null in LINQ

查看:282
本文介绍了如果LINQ中的列为空,如何忽略"where"和"order by"条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有交易对象的列表,并希望根据特定的视图用户当前所处的状态来对它们进行排序.

I have list of transaction objects and want to order them by certain condition depending on view user is currently on.

我遇到的问题是,为了在where子句中添加条件,首先我需要检查它是否为null或防止空指针异常.这会导致过滤出具有null列的记录(我想将它们包括在列表的底部).

The problem I have is that in order to add a condition in a where clause, first I need to check if it is null or not to prevent null pointer exception. This causes records with the column null being filtered out(and I want to include them at bottom of the list).

如果该列为空,如何修改查询以使其忽略条件(在何处和排序依据),并且仍将其附加到结果集中?

How can I modify the query so that it ignores the conditions(where and order by) if that column is null and still append them to the result set?

这是一个示例查询:

transactions = transactions
                    .Where(t => t.PurchaseRequisition != null && 
                    t.Award != null && t.PurchaseRequisition.RequisitionedBy != null)
                    .OrderBy(t => t.Award.ContractNumber).
                    ThenBy(t => ToSafeString(t.Award.ContractNumber)).
                    ThenBy(t => ToSafeString(t.PurchaseRequisition.RequisitionedBy.FullName));


public string ToSafeString(string s)
{
    return s ?? String.Empty;
}

//我希望将PurchaseRequisition或Award为null的记录添加到结果集中.

// I want records where PurchaseRequisition or Award is null to be appended to the result set.

推荐答案

您只需要修改OrderByThenBy子句:

.OrderBy(t => t.Award == null || t.Award.ContractNumber == null)
.ThenBy(t => t.Award == null ? "" : ToSafeString(t.Award.ContractNumber))
.ThenBy(t => t.PurchaseRequisition == null ? "" 
             : ToSafeString(t.PurchaseRequisition.RequisitionedBy.FullName));

现在您可以完全删除Where子句.

Now you can completely remove the Where clause.

这篇关于如果LINQ中的列为空,如何忽略"where"和"order by"条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆