Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search string not in char array using LinQ

Tags:

c#

list

linq

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"

like image 586
Slocky Avatar asked Dec 13 '22 15:12

Slocky


1 Answers

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);
like image 181
Tim Schmelter Avatar answered Dec 29 '22 10:12

Tim Schmelter