Jeremy Stein
Jeremy Stein

Reputation: 19661

Best way to check for string in comma-delimited list with .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.)

Upvotes: 28

Views: 75576

Answers (9)

Ambala Chandrashekar
Ambala Chandrashekar

Reputation: 532

                 public bool GetIsExistSubstring(string mainstring, string substring)
    {        
        bool Isexist=false;
        int i = -1;
        mainstring = string.Format(",{0},", mainstring);//so it will be like  ,1,2,3,
        substring = string.Format(",{0},", substring);//so it will be like  ,1,
        i=mainstring.IndexOf(substring);

        if(i!=-1)
        {
            Isexist = true;
        }
        return Isexist;
    }

Upvotes: 0

Vivek
Vivek

Reputation: 641

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
}

Upvotes: 0

Damian Powell
Damian Powell

Reputation: 8775

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

Upvotes: 2

Fábio Batista
Fábio Batista

Reputation: 25270

Using linq:

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

W/o linq:

Array.IndexOf(listString.Split(','), "apple") >= 0

Upvotes: 51

Jeremy Stein
Jeremy Stein

Reputation: 19661

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) + "(?=,|$)")

Upvotes: 8

David
David

Reputation: 25460

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.

Upvotes: 1

Austin Salonen
Austin Salonen

Reputation: 50225

Here's an option that ignores case.

var food = "apple,banana,cheese";

bool containsApp = food.Split(',')
                       .Where(s => string.Compare("app", s, true) == 0)
                       .Count() > 0;

bool containsApple = food.Split(',')
                         .Where(s => string.Compare("apple", s, true) == 0)
                         .Count() > 0;

Console.WriteLine("Contains \"app\"? {0}", containsApp);
Console.WriteLine("Contains \"apple\"? {0}", containsApple);

Upvotes: 1

Adriaan Stander
Adriaan Stander

Reputation: 166406

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

Upvotes: 3

nothrow
nothrow

Reputation: 16168

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

but not straight-forward, too.

Upvotes: 13

Related Questions