c# - 从字符串列表中删除空条目
问题描述
我正在寻找一种更有效的方法来从字符串列表中删除空字符串值。
下面的代码有效,但对于非常大的数据集,这似乎效率低下。有没有更有效的方法来做到这一点?
仅供参考 - 开始只是构建一个数据集以具有一个包含空字符串的列表列表
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()方法?定义:
删除与指定谓词定义的条件匹配的所有元素。
foreach (var l in list)
{
l.RemoveAll(x => string.IsNullOrEmpty(x));
}
这就是你所需要的。其他答案 have Select().Where()
and two ToList()
,这对于像这样的简单操作来说开销太大了。
推荐阅读
- c++ - 编辑 LLVM 代码时 VS Code 语法突出显示损坏
- r - 是否可以在 ggplot 中创建一个带有 x 和 y 方向置信区间的 geom_errorbar 散点图?
- powershell - 使用 PowerShell 将多值属性数组提取到 csv 文件
- javascript - 你有这个 React-Three-Fiber Slider 的解决方案吗?
- sas-jmp - jmp 脚本逻辑可用作 jsl,但不能用作插件
- mysql - 仅当两个表中有一个匹配记录时才加入
- templates - Docusign API 问题:添加 addtl。将文档放入信封与使用复合模板
- matplotlib - 在 Matplotlib 热图中定义次要刻度时,网格线未与单元格对齐
- python - pip3:这些包是什么?
- google-chat - [Google Chat]发布 googleChat 机器人时出现未列出的错误