我正在寻找一种更有效的方法从字符串列表中删除空字符串值.
下面的代码可以工作,但对于非常大的数据集,这似乎效率低下.有没有更有效的方法来做到这一点?
仅供参考 - 开始只是构建一个数据集,以包含一个包含空字符串的列表
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"
*/
}
Run Code Online (Sandbox Code Playgroud)
为什么不使用List <T> .RemoveAll()方法?定义:
删除与指定谓词定义的条件匹配的所有元素.
foreach (var l in list)
{
l.RemoveAll(x => string.IsNullOrEmpty(x));
}
Run Code Online (Sandbox Code Playgroud)
这就是你所需要的一切.其他答案有Select().Where()两次ToList(),这对于像这样的简单动作来说是太多的开销.
| 归档时间: |
|
| 查看次数: |
849 次 |
| 最近记录: |