开发者

C# Split String and Use in If Statement

开发者 https://www.devze.com 2023-02-14 11:50 出处:网络
Is there a more elegant way to accomplish this. I have a string, where I would like to split and use individually in an i开发者_运维问答f statement. For example:

Is there a more elegant way to accomplish this.

I have a string, where I would like to split and use individually in an i开发者_运维问答f statement. For example:

string people = "John;Joe;Jane;Mike";
string[] names = people.Split(';');

if(person == "John" || person == "Joe" || person == "Jane" || person == "Mike")
{
    ....
}
else
{
    ....
}

There's a better way of doing this, I guess.

Thanks.


if(names.Contains(person)) { ... }


string people = "John;Joe;Jane;Mike";
string[] names = people.Split(';');

if(names.Contains(person))
{
    ....
}
else
{
    ....
}

Contains<T> is an extension method of IEnumerable<T> (and an array is an IEnumerable<T>) so you can use it on the result of Split to check if it contains the string you are looking for.


string people = "John;Joe;Jane;Mike";
List<string> names = new List<string>(people.Split(';'));

if(names.Contains(person))
{
    ....
}
else
{
    ....
}

Collections are your friends :)


This would do it:

if(names.Contains(person))


Do this:

string people = ";John;Joe;Jane;Mike;"; 
string findPerson = "Joe";

if (people.contains(String.Format(";{0};", findPerson)) {
  ... it's found...
} else {
  ... it's not found ....
}

note that I added the delimiters to the beginning and ending of the original string. Also, we're appending the delimiters to the beginning and end of the findPerson variable. This ensures that we don't hit on a partial match. For example finding "chris" in "christoph"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号