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

后端 未结 9 1364
没有蜡笔的小新
没有蜡笔的小新 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:12

    The answer depends on what the syntax rules for your comma-delimited list are.

    If the rules require that the list be exactly as you posted (no spaces, no trailing comma) then the task can be broken down into it's component pieces:

    Does the string begin with apple,? (String.StartsWith)
    Does the string end with ,apple? (String.EndsWith)
    Does the string contain ,apple,? (String.Contains)

    If the rules are more difficult then the Regex approach becomes the only way without fully processing the list or writing a heap of rules.

    If you are checking for many items against the same string you'll want to just transform the string into a list which you cache and then check against. The String.Split method will do this for you.

提交回复
热议问题