Search code examples
c#.netstringliststartswith

Check that string does not start with any letters from List<string>


If I have input a string is it possible to check that the first letter does start with an input from a list of strings:

var dir = "FOLDERNAME";
var list = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "s", 
                                "t", "u", "v", "w", "z", "y", "z", 
                                "1", "2", "3", "4", "5", "6", "7", "8", "9"};
if (!dir.ToLower().!StartsWith :MagicLinq: list) { Do Stuff; }

Or do I have to go the regex route?


Solution

  • One approach to consider:

    var lower = new string(dir?.FirstOrDefault() ?? new char(), 1);
    if (list.Contains(lower) {
    

    The first line gets the first character from the string, and handles empty and null strings (by getting the null char), and then loads that char into a string.

    You could simplify that if the List<string> was a List<char or HashSet<char> instead. Then you could remove the new string part.