You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LINQ中处理可空Guid(Guid?)的查询优化及警告消除问题

解决Guid?类型LINQ查询的空警告问题

原代码通过强制转换(Guid)x.Status访问IsEmpty(),既没有覆盖Status为null的场景,还会触发“可空类型可能为null”的警告。以下几种写法可以同时解决警告问题,并实现获取Status为null或Guid.Empty的预订列表:

方法一:显式判断null与Empty

先判断Status是否为null,再安全访问Value属性(编译器会识别前置的null判断,不会触发警告):

bookings = bookings
    .Where(x => x.Status == null || x.Status.Value.IsEmpty())
    .ToList();

方法二:使用GetValueOrDefault()简化判断

GetValueOrDefault()会在Status为null时返回Guid.Empty,因此一次判断即可覆盖两种场景,且无需强制转换:

bookings = bookings
    .Where(x => x.Status.GetValueOrDefault().IsEmpty())
    .ToList();

方法三:C# 8.0+模式匹配写法

利用模式匹配语法让代码更简洁直观,同样不会触发空警告:

bookings = bookings
    .Where(x => x.Status is null or { Value: { IsEmpty: true } })
    .ToList();

内容的提问来源于stack exchange,提问作者Jason Hunter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:22:43