Consider the requirement to strip invalid characters from a string. The characters just need to be removed and replace with blank or string.Empty
.
Why would you have REALLY LIKED to do that? The code is absolutely no simpler, you're just forcing a query extension method into your code.
As an aside, the Contains
check seems redundant, both conceptually and from a performance perspective. Contains
has to run through the whole string anyway, you may as well just call Replace(bad.ToString(), string.Empty)
for every character and forget about whether or not it's actually present.
Of course, a regular expression is always an option, and may be more performant (if not less clear) in a situation like this.
char[] BAD_CHARS = new char[] { '!', '@', '#', '$', '%', '_' }; //simple example
someString = string.Concat(someString.Split(BAD_CHARS,StringSplitOptions.RemoveEmptyEntries));
should do the trick (sorry for any smaller syntax errors I'm on my phone)
Extra tip: If you don't want to remember the array of char
that are invalid for Files, you could use Path.GetInvalidFileNameChars()
. If you wanted it for Paths, it's Path.GetInvalidPathChars
private static string RemoveInvalidChars(string str)
{
return string.Concat(str.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries));
}