简体   繁体   English

Lambda WHERE子句中的空值

[英]Null value in lambda WHERE clause

How can we avoid null exceptions when using Lambda queries? 使用Lambda查询时,如何避免空异常? In the below code when InstallationDateType is null I get an exception. 在以下代码中,当InstallationDateType为null时,我得到一个异常。 How do I tackle with this? 我该如何解决?

foreach (AvailableDate availableDate in installationDatesResponseRootObject.Response
              .InstallationDatesResponse
              .AvailableDates
              .Where(a => 
                  a.InstallationDateType.ToString().ToUpper() == Constants.InstallationDateTypeDish))
{
    //Do Something
}

Try to use Null-Conditional Operator ?. 尝试使用空条件运算符?. introduced in C# 6. 在C#6中引入。

In your example it would be 在您的示例中

a.InstallationDateType?.ToString().ToUpper().Equals(Constants.InstallationDateTypeDish)

Check if installationDatesResponseRootObject, Response, InstallationDatesResponse, AvailableDates aren't nulls. 检查installationDatesResponseRootObject,Response,InstallationDatesResponse,AvailableDates是否不为空。 Then change your LINQ into this: 然后将您的LINQ更改为:

 installationDatesResponseRootObject.Response.InstallationDatesResponse.AvailableDates.Where(a => a.InstallationDateType!=null && a.InstallationDateType.ToString().ToUpper() == Constants.InstallationDateTypeDish))

To elaborate on my comment, here is an example: 为了详细说明我的评论,下面是一个示例:

var items = installationDatesResponseRootObject.Response.InstallationDatesResponse.AvailableDates
    .Where(a => a.InstallationDateType?.ToString().ToUpper() == Constants.InstallationDateTypeDish);
if (items.Any())
    foreach (var item in items)
    {
          //Do something
    }

Note that this is only an example. 注意,这仅是示例。 There are better ways to check if the IEnumerable is empty or not. 有更好的方法来检查IEnumerable是否为空。

The issue is because you are called .ToString() on a null reference, so you need to check for this first. 问题是因为在null引用上将您称为.ToString() ,因此您需要首先进行检查。

There are a few different ways of checking. 有几种不同的检查方法。 If you're using the latest C# then you're probably better off using the Null-Conditional Operator ?. 如果您使用的是最新的C#,则最好使用Null-Conditional Operator ?. introduced in C# 6 as mentioned by slanto. 如slanto所述,是在C#6中引入的。

If you are using an older version of C# then you can just do it in your Where method as below. 如果您使用的是C#的旧版本,则可以在下面的Where方法中进行操作。

foreach (AvailableDate availableDate in installationDatesResponseRootObject.Response.InstallationDatesResponse.AvailableDates.Where(a => a.InstallationDateType != null && a.InstallationDateType.ToString().ToUpper() == Constants.InstallationDateTypeDish))
{
    //Do Something
}

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM