使用 linq 的 where 方法配合 string.isnullorwhitespace 可以过滤掉只含空白的元素。调用 list.where(s => !string.isnullorwhitespace(s)).tolist() 即可得到清理后的新列表,原列表保持不变。

IsNullOrWhiteSpace 与 Trim().Length == 0 的区别是什么
IsNullOrWhiteSpace 会检查 null、空字符串以及包含空白字符(如空格、制表符)的字符串,而 Trim().Length == 0 仅处理非 null 且仅含空白字符的情况。对于 null 输入,前者返回 true,后者会抛出异常。

using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<string> list = new List<string> { "hello", " ", "\t", "world", null, "" };
var filtered = list.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
foreach (var s in filtered) Console.WriteLine(s);
}
}
如何原地删除 List<string></string> 中的空白元素
使用 RemoveAll 方法可以直接修改原列表,移除所有满足条件的元素。传入 s => string.IsNullOrWhiteSpace(s) 作为谓词,该方法返回被移除的元素数量。
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<string> list = new List<string> { "a", " ", "b", "\n", "c" };
int removed = list.RemoveAll(s => string.IsNullOrWhiteSpace(s));
Console.WriteLine($"Removed: {removed}, Remaining: {list.Count}");
}
}


















