Alex Rivera | Logout

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

Asked 2010-04-06T16:44:30.437
28

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"

If I check for "apple" I should find it, but if I check for "app" I should not.

What's the most straight-forward and concise way to do this? It doesn't have to be fast.

(I'll add my solution as an answer, but I'm hoping someone has something better.)

Edit
Report

3 Answers

51

Using linq:

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

W/o linq:

Array.IndexOf(listString.Split(','), "apple") >= 0
answered 2010-04-06T16:48:24.123
8

Regex probably doesn't count as "straight-forward", but this is what I've got:

Regex.IsMatch(listString, "(?<=,|^)" + testWord + "(?=,|$)")

Update: Per Eric's comment below, this should be:

Regex.IsMatch(listString, "(?<=,|^)" + Regex.Escape(testWord) + "(?=,|$)")
answered 2010-04-06T16:44:36.537
3

Another way might be to try using

bool contains = new List<string>("apple,banana,cheese".Split(',')).Contains("apple");
//or
bool b = "apple,banana,cheese".Split(',').Contains("apple");

List< T>.Contains Method

String.Split Method

Enumerable.Contains Method

answered 2010-04-06T16:49:50.423

Your Answer