我正在寻找一种更高效的方法来从一个字符串列表的列表中删除空字符串值。
下面的代码可以工作,但是对于非常大的数据集来说,这似乎是低效的。 是否有更有效的方法可以做到这一点? 注意 - 开头只是构建数据集,以便拥有包含空字符串的列表
下面的代码可以工作,但是对于非常大的数据集来说,这似乎是低效的。 是否有更有效的方法可以做到这一点? 注意 - 开头只是构建数据集,以便拥有包含空字符串的列表
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.RemoveAll()
,这样您就不需要创建新的列表来替换当前的列表。 - Jeff MercadoRemoveAll
方法应该是您的首选。 - Eric Lippert