I have very large string lists and arrays and i found 2 issues that i want to resolve:
- Remove all entries that are blank strings
- Remove all entries that are just whitespace
These can be 2 different solution . . not sure if there is a faster way compared to a basic loop or this:
array = array.Where(r=>!String.IsNullOrEmpty(r.Trim());
For a
List<T>there’s a potentially-faster equivalent, which performs the removal in-place,RemoveAll:This may be faster in terms of how the repositioning within the list is performed.
It also depends on whether you want in-place removal, of course. Personally I’d normally prefer the LINQ approach as it’s more flexible and more idiomatic these days – I usually treat collections as immutable sequences, even if they’re not really 🙂
One point to note: you don’t need to trim a string to find out whether or not it’s got any whitespace. You can use
string.IsNullOrWhiteSpace, which should really be calledIsNullOrEmptyOrWhitespace– basically “does it not have content”.This could easily make a very significant difference to performance – if you have a lot of long strings, there’s no point in having an O(N) operation (
Trim) just to determine that there’s some content… and there’s no point creating a new string when you’re just going to throw it away again.Note: sizes changed from earlier version to give good differentiation between final three cases…
Here’s an example:
Sample results on my laptop: