Best way to check for string in comma-delimited list with .NET?

后端 未结 9 1360
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 09:37

I\'m reading a comma-delimited list of strings from a config file. I need to check whether another string is in that list. For example:

\"apple,banana,cheese\"
相关标签:
9条回答
  • 2021-02-02 10:31

    Using linq:

    listString.Split(',').Contains("apple")
    

    W/o linq:

    Array.IndexOf(listString.Split(','), "apple") >= 0
    
    0 讨论(0)
  • 2021-02-02 10:31

    This works, but regexes are pretty slow if they get complicated. That said, the word boundary anchor makes this sort of thing pretty easy.

    var foods = "apple,banana,cheese";
    
    var match = Regex.Match(foods, @"\bapple\b");
    
    if (match.Success)
        Console.WriteLine(match.Value);
    
    0 讨论(0)
  • 2021-02-02 10:32

    This is solution for ignoring case and culture(or select one of the property of StringComparer)

    var commaDelimitedString = "string1,string2,string3,string4";
    var testString = string2.trim; // trim to remove the spaces coz you may be getting it from UI
    if(commaDelimitedString.split(',').contains(testString,StringComparer.InvariantCultureIgnoreCase))
    {
         //TODO: What to do when condition is true
    }
    else
    {
         //TODO: What to do when condition is false
    }
    
    0 讨论(0)
提交回复
热议问题