我正在寻找一种更有效的方法来从字符串列表中删除空字符串值。
下面的代码有效,但对于非常大的数据集,这似乎效率低下。有没有更有效的方法来做到这一点?
仅供引用 - 开始只是构建一个数据集以包含一个包含空字符串的列表
public static void Main()
{
//Building the data set
List<List<string>> list = new List<List<string>>();
list.Add(new List<string> {"One", "Two", "", "Eight"});
list.Add(new List<string> {"Three", "Five", "Six"});
list.Add(new List<string> {"Sixteen", "", ""});
list.Add(new List<string> {"Twenty-Eight", "Forty", "Nine"});
//Create an empty List of a List
List<List<string>> newList = new List<List<string>>();
//Loop through the original list and purge each list of empty strings
for(int i = 0; i < list.Count; i++) {
newList.Add(list[i].Where(x => !string.IsNullOrEmpty(x)).ToList());
}
foreach (var s in newList) {
Console.WriteLine(string.Join(", ", s));
}
/*
CORRECT OUTPUT:
"One", "Two", "Eight"
"Three", "Five", "Six"
"Sixteen"
"Twenty-Eight", "Forty", "Nine"
*/
}
最佳答案
为什么不使用 List<T>.RemoveAll()方法?定义:
Removes all the elements that match the conditions defined by the specified predicate.
foreach (var l in list)
{
l.RemoveAll(x => string.IsNullOrEmpty(x));
}
这就是您所需要的。其他答案有 Select().Where()
和两次 ToList()
,这对于像这样的简单操作来说开销太大了。
关于c# - 从字符串列表中删除空条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52936210/