c# - 从字符串列表中删除空条目

标签 c# list linq

我正在寻找一种更有效的方法来从字符串列表中删除空字符串值。

下面的代码有效,但对于非常大的数据集,这似乎效率低下。有没有更有效的方法来做到这一点?

仅供引用 - 开始只是构建一个数据集以包含一个包含空字符串的列表

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/

相关文章:

c# List<Tuple<string, string, int>> group by min max int

c# - Linq 查询连接不起作用

c# - 我如何通过Linq C#获得每个数组的第一个元素

c# - 解码 LINQ 的服务?

c# - WCF 与 Java 兼容吗?

c# - Azure 通知中心为 WNS 注册原始模板

c# - 查找默认电子邮件客户端

c# - linq to sql vs 存储过程的效率

python - 将所有嵌套列表调整为相同的长度

java - 使用HashMap和List解析文本文件