首页 > 解决方案 > 从字符串列表中删除空条目

问题描述

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

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

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

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"         
    */      
}

标签: c#listlinq

解决方案


为什么不使用List<T>.RemoveAll()方法?定义:

删除与指定谓词定义的条件匹配的所有元素。

foreach (var l in list)
{
    l.RemoveAll(x => string.IsNullOrEmpty(x));
}

这就是你所需要的。其他答案 have Select().Where()and two ToList(),这对于像这样的简单操作来说开销太大了。


推荐阅读