使用 list 方法并传入 t => t.property == null 谓词即可原地删除属性为空的对象。该方法会遍历列表,移除所有满足条件的元素并返回被移除的数量,无需创建新集合。

RemoveAll 如何处理空值与性能开销
RemoveAll 通过内部数组移位实现删除,时间复杂度为 O(N)。对于大型列表,频繁调用会导致大量内存拷贝,此时应考虑使用 LINQ 的 Where 过滤后重新赋值或转换为数组。

using System;
using System.Collections.Generic;
public class Item {
public string Name { get; set; }
}
public class Program {
public static void Main() {
var list = new List<item> {
new Item { Name = "A" },
new Item { Name = null },
new Item { Name = "B" }
};
int removed = list.RemoveAll(x => x.Name == null);
Console.WriteLine($"Removed: {removed}, Count: {list.Count}");
}
}
</item>
预期输出:
Removed: 1, Count: 2
LINQ Where 过滤与原地删除的区别
LINQ Where 返回新枚举,不修改原列表。若需更新原引用,需将结果重新赋值给变量或容器。这种方式代码更简洁,但会产生额外内存分配。

using System;
using System.Collections.Generic;
using System.Linq;
public class Item {
public string Name { get; set; }
}
public class Program {
public static void Main() {
var list = new List<item> {
new Item { Name = "A" },
new Item { Name = null },
new Item { Name = "B" }
};
// 方式二:LINQ 过滤
var filteredList = list.Where(x => x.Name != null).ToList();
Console.WriteLine($"Filtered Count: {filteredList.Count}");
}
}
</item>
预期输出:
Filtered Count: 2
当属性为引用类型时如何安全判断空值
在 C# 8.0+ 中,可使用可空引用类型 ? 标记。判断时应区分 null 和空字符串 string.Empty。若属性为值类型(如 int?),需检查 .HasValue 或 == null。










