Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.)

like image 759
Jeremy Stein Avatar asked Apr 06 '10 16:04

Jeremy Stein


People also ask

How do you value a comma separated string?

To check if value exists in a comma separated list, you can use FIND_IN_SET() function. Now you can insert some records in the table using insert command. Display all records from the table using select statement.

How do you check if a string contains a character C#?

To check if a string str contains specified character value , or say if specified character is present in the string, use C# String. Contains(Char) method. Call Contains() method on the string str and pass the character value as argument. Contains() method returns True if str contains value .


2 Answers

Using linq:

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

W/o linq:

Array.IndexOf(listString.Split(','), "apple") >= 0 
like image 177
Fábio Batista Avatar answered Oct 09 '22 02:10

Fábio Batista


(","+listString+",").Contains(","+testWord+","); 

but not straight-forward, too.

like image 35
nothrow Avatar answered Oct 09 '22 03:10

nothrow