Reputation: 747
If I want to assign the same value to multiple objects, I use something like this:
string1 = string2 = string3 = string 4 = "some string";
I want to compare string1, string2, string3, and string4 with "someotherstring". Is there any way to do this without writing individual comparisons? i.e.
string1 == "someotherstring" || string2 == "someotherstring" || string3 == "someotherstring" || string4 == "someotherstring"
Upvotes: 6
Views: 7935
Reputation: 46526
I find LINQ very expressive, and would consider using it for this problem:
new[] { string1, string2, string3, string4 }.Any(s => s == "some string")
Upvotes: 5
Reputation: 12971
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
}
Upvotes: 15
Reputation: 16994
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 );
Upvotes: 1
Reputation: 166406
For your case you can try something like this
if (new string[] { string1, string2, string3, string4 }.Contains("someotherstring"))
{
}
Upvotes: 8
Reputation: 21141
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.
Upvotes: 0
Reputation: 1217
No there isn't in C# but you could write it this way:
(string1 == string2 && string2 == string3 &&
string3 == string4 && string4 == "someotherstring")
Upvotes: 3