I'm looking for a more efficient way of removing empty string values from a list of a list of strings.
The code below works but for a very large data set this seems inefficient. Is there a more efficient way to do this?
FYI - The beginning is just to build a Data Set to have a list of a list that contains empty strings
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"
*/
}
Why not use the List<T>.RemoveAll() method? Definition:
Removes all the elements that match the conditions defined by the specified predicate.
foreach (var l in list)
{
l.RemoveAll(x => string.IsNullOrEmpty(x));
}
That is all you need. Other answer have Select().Where()
and twice ToList()
, which is way too much overhead for a simple action like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With