I've come across this several times in the past and have finally decided to find out why.
StringSplitOptions.RemoveEmptyEntries
would suggest that it removes empty entries.
So why does this test fail?
var tags = "One, Two, , Three, Foo Bar, , Day , "; var tagsSplit = tags.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Trim()); tagsSplit.ShouldEqual(new string[] { "One", "Two", "Three", "Foo Bar", "Day" });
The result:
Values differ at index [2] Expected string length 5 but was 0. Strings differ at index 0. Expected: "Three" But was: <string.Empty>
So it fails because instead of "Three"
, we have an empty string – exactly what StringSplitOptions.RemoveEmptyEntries
should prevent.
Most likely because you change the string after the split. You trim the values after splitting them, RemoveEmptyEntries
doesn't consider the string " "
empty.
The following would achieve what you want, basically creating your own strip empty elements:
var tagsSplit = tags.Split(','). Select(tag => tag.Trim()). Where( tag => !string.IsNullOrEmpty(tag));
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