在LinQ中检查null

时间:2012-03-27 03:40:05

标签: c# linq

这是我的疑问:

var entityMerchantVisit =
     from e in context.MerchantCustomerVisit
     where e.CustomerId == currentCustGuid
     group e by  
           new { e.Merchant.Locations.FirstOrDefault().CityId } into mcvGroup
     orderby mcvGroup.Count() descending
     select mcvGroup;

我收到错误

  

“当 e.Merchant.Locations.FirstOrDefault()。CityId 为空时,转换为值类型'Int32'失败,因为物化值为空”。

我如何检查它是否为空。如果它为空,我想将其指定为(int) 0

4 个答案:

答案 0 :(得分:4)

这样的事情可行:

var entityMerchantVisit =
     from e in context.MerchantCustomerVisit
     where e.CustomerId == currentCustGuid
     group e by  
           new { e.Merchant.Locations.FirstorDefault() != null 
                  ? e.Merchant.Locations.First().CityId : 0
               } into mcvGroup
     orderby mcvGroup.Count() descending
     select mcvGroup;

根据您的评论,您可以尝试以下方法(请注意括号):

     group e by  
           new { CityID = ((int)e.Merchant.Locations.FirstorDefault() != null 
                  ? e.Merchant.Locations.First().CityId : 0)
               } into mcvGroup
     orderby mcvGroup.Count() descending

答案 1 :(得分:4)

您可以使用let语法将e.Merchant.Locations.FirstOrDefault()绑定到范围变量,然后检查是否为null。这使您可以方便地识别没有位置的商家,并为您提供一个简洁的三元运算符表达式来启动。

var entityMerchantVisit =
     from e in context.MerchantCustomerVisit
     where e.CustomerId == currentCustGuid
     let location = e.Merchant.Locations.FirstOrDefault()
     group e by  
           new { CityId = (location == null ? 0 : location.CityId) } into mcvGroup
     orderby mcvGroup.Count() descending
     select mcvGroup;

答案 2 :(得分:0)

使用空合并运算符(??)

var entityMerchantVisit =
 from e in context.MerchantCustomerVisit
 where e.CustomerId == currentCustGuid
 group e by  
       new { (e.Merchant.Locations.FirstOrDefault().CityId ?? 0) } into mcvGroup
 orderby mcvGroup.Count() descending
 select mcvGroup;

答案 3 :(得分:0)

您可以尝试使用Nullable<int>表达式:

var entityMerchantVisit =
    from e in context.MerchantCustomerVisit
    where e.CustomerId == currentCustGuid
    group e by new {
        CityId = e.Merchant.Locations.Any() ? 
            e.Merchant.Locations.First().CityId
            : default(int?)
    } into mcvGroup
    orderby mcvGroup.Count() descending
    select mcvGroup;