我有这个:
List<string> s = new List<string>{"", "a", "", "b", "", "c"};
我想快速地从中删除所有空元素("")
,最好使用LINQ而不是foreach
语句,因为后者会让代码看起来很丑陋。
List.RemoveAll
方法:
C#
C#
s.RemoveAll(str => String.IsNullOrEmpty(str));
VB.NET
s.RemoveAll(Function(str) String.IsNullOrEmpty(str))
s.RemoveAll(String.IsNullOrEmpty);
,不需要使用lambda表达式。 - Paolo Morettis.RemoveAll(AddressOf String.IsNullOrEmpty)
,而且 lambda 表达式表明可以轻松修改它。在我看来,使用 lambda 更易读。 - Tim Schmelterint count = s.RemoveAll(string.IsNullOrEmpty);
是有效的,但是 List<string> list = s.RemoveAll(string.IsNullOrEmpty);
不是。 - Jan Chalupa使用 List.RemoveAll
方法结合 String.IsNullOrEmpty()
方法进行检查;
指示指定的字符串是 null 还是 Empty 字符串。
s.RemoveAll(str => string.IsNullOrEmpty(str));
这里有一个演示
。
s = s.Where(val => !string.IsNullOrEmpty(val)).ToList();
List<string>
,需要确保它仍然是一个 List<string>
。 - MethodManList<string> s = new List<string>{"", "a", "", "b", "", "c"};
s = s.Where(t => !string.IsNullOrWhiteSpace(t)).Distinct().ToList();