开发者

C# Multiple String Comparision with Same Value

Please have a look at the below case, surely that will be interesting..

if i want to assign same value to multiple objects i will use something like this

string1 = string2开发者_StackOverflow = string3 = string 4 = "some string";

Now what i want to do is, i want to compare string1, string2, string3 and string4 with "someotherstring"... questions is is there any way to do this without writing individual comparision. i.e.

string1 == "someotherstring" || string2 == "someotherstring" || string3 == "someotherstring" || string4 == "someotherstring"

Hope i was able to explain the question.. kindly provide me help on this.

Regards, Paresh Rathod


In C# 3.0, you can write a very trivial extension method:

public static class StringExtensions
{
    public static bool In(this string @this, params string[] strings)
    {
        return strings.Contains(@this); 
    }
}

Then use it like this:

if ("some string".In(string1, string2, string3, string4))
{
    // Do something
}


For your case you can try something like this

if (new string[] { string1, string2, string3, string4 }.Contains("someotherstring"))
{
}


I find LINQ very expressive, and would consider using it for this problem:

new[] { string1, string2, string3, string4 }.Any(s => s == "some string")


No there isn't in C# but you could write it this way:

 (string1 == string2 && string2 == string3 && 
  string3 == string4 && string4 == "someotherstring")


You can create a function that simplifies reading the code :

compareToFirst( "someotherthing", string1, string2, string3, string4);

If you want to compare this list of strings to successive "other strings", you may want to create a list object "myStringList" in which you'd add string1/2/3/4 then define a function to be able to write

compare( "someotherthing", myStringList );


I do not believe so. How would you know which one did not compare or did match. There would be no way to evaluate the side-effect of such a comparison.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜