最直接安全的空值过滤方式是.where(s => !string.isnullorempty(s)),可排除null和空字符串;需注意返回ienumerable需转tolist()才能多次使用,原地过滤用removeall(),混类型时需oftype()或is string检查。

用 Where 过滤 List<string></string> 中的空值最直接
对 List<string></string> 做空值过滤,.Where(s => !string.IsNullOrEmpty(s)) 是最常用也最安全的方式。它能同时排除 null、空字符串 "" 和只含空白字符的字符串(如果你需要后者,得额外处理)。
常见错误是只写 s != null 或 !string.IsNullOrWhiteSpace(s) 却没想清楚语义差异:
-
string.IsNullOrEmpty(s):只判断null或"",不处理"\t\n " -
string.IsNullOrWhiteSpace(s):多一步 Trim 后判空,性能略低,但更严格 - 直接访问
s.Length会触发NullReferenceException,必须先判空
Where 在 List<t></t> 上的返回类型不是 List<t></t>
.Where(...) 返回的是 IEnumerable<t></t>,不是新的 List<t></t>。如果后续要多次遍历、或调用 .Count、.Add 等方法,必须显式转成 List:
var filtered = myList.Where(s => !string.IsNullOrEmpty(s)).ToList();
漏掉 .ToList() 容易导致重复执行(比如在 for 循环里反复调用 Where),或编译报错(如 filtered.Add(...) 报错:“IEnumerable<string></string> 不包含 Add”)。
原地过滤用 RemoveAll,但注意返回值和副作用
如果不想新建列表,而是直接修改原 List<string></string>,用 .RemoveAll() 更高效:
int removedCount = myList.RemoveAll(s => string.IsNullOrEmpty(s));
它返回被移除元素个数,方便做断言或日志;但要注意:
- 原列表顺序不变,只是中间“空洞”被压缩
- 操作不可逆,没有副本,多线程下需加锁
- 不能用
string.IsNullOrWhiteSpace替换条件——逻辑一样,但性能差一点,尤其数据量大时
泛型 List<object></object> 或自定义类型要小心类型检查
如果列表是 List<object></object>,且里面混了 string 和其他类型,string.IsNullOrEmpty(s) 会编译失败(因为 s 是 object)。此时得先做类型转换:
var stringsOnly = list.OfType<string>().Where(s => !string.IsNullOrEmpty(s)).ToList();</string>
或者用 as 安全转换:
var filtered = list.Where(o => o is string s && !string.IsNullOrEmpty(s)).Cast<string>().ToList();</string>
别用 (string)o 强转——遇到非字符串会抛 InvalidCastException。
真正容易被忽略的,是空值判定逻辑和实际业务是否一致:比如前端传来的 "undefined" 或 "null" 字符串,它们不是 null,也不会被 IsNullOrEmpty 拦住。这种得单独 .Replace 或正则清洗。











