List<string> words = new List<string> { "abc", "acb", "cba", "cb a", "abf", "sea", "aba", "so ap", "a b c" };
string allowedChars = "abc";
I want to check invalid charachters in list string. I try use IndexOfAny() but IndexOfAny() does not check white space. How to check string which contains invalid charachters?
The result I want: "cb a", "abf", "sea", "so ap", "a b c"
var invalid = words.Where(w => !w.All(allowedChars.Contains));
It checks for every word if there is at least one char in it which is not contained in allowedChars
.
This is the same but little bit more verbose:
var invalid = words.Where(w => w.Any(c => !allowedChars.Contains(c)));
Both stop execution if they found the first char that is not contained.
As Juharr has noted, if there are many characters allowed you could make it more efficient by using a HashSet<char>
instead of the String
:
var alloweCharSet = new HashSet<char>(allowedChars);
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