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

List.Where().ToList()触发Null Reference Exception问题求助

问题分析与解决

你的空引用异常不是来自totalEmployeeList本身,而是**totalEmployeeList中存在null的Employees对象**。当Where遍历列表时,遇到null的x,访问x.department就会触发空引用异常——堆栈信息显示在ToList()方法里,是因为异常是在Linq迭代过程中抛出的,最终在ToList调用时暴露出来。

修复代码

在Where的过滤条件里先判断x是否非空,再校验部门:

List<Employees> marketingEmployeeList = new List<Employees>();
if (totalEmployeeList != null && totalEmployeeList.Any())
{
    // 先排除null的Employees对象,再过滤部门
    marketingEmployeeList = totalEmployeeList.Where(x => x != null && x.department == "Marketing").ToList();
}
if(marketingEmployeeList.Any())
{
    CallMethod(marketingEmployeeList);
}

额外注意点

  • 代码里的If是大写,C#中关键字是小写if,虽然这不是本次异常的原因,但实际编译时会报错,建议修正。
  • 如果totalEmployeeList是被多线程修改的集合,可能出现遍历过程中元素变为null的情况,这种情况下需要考虑线程安全,比如遍历前加锁或者使用线程安全集合。

内容的提问来源于stack exchange,提问作者Gladstone Jaffrey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:37:12