tags:

views:

235

answers:

6

Hi All.

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 = 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 KlixMedia

+2  A: 

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

 (string1 == string2 && string2 == string3 && 
  string3 == string4 && string4 == "someotherstring")
James Keesey
Hi James..Thanks for your reply..If you will take a look again at my question.. i have used ||. Means, any of string1, string2, string3 and string4 should be equal to "someotherstring"...I think that.. your case will be applicable if i want to check, whether all 4 string instances are equal to "someotherstring" or not?Am i right?Regards,Paresh RathodKlixMedia
Paresh Rathod
You're right, I misread it. See astander's below.
James Keesey
A: 

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.

GrayWizardx
+5  A: 

For your case you can try something like this

if (new string[] { string1, string2, string3, string4 }.Contains("someotherstring"))
{
}
astander
Very Tricky. ;-)
James Keesey
and for an "and" operation: strings.All(x => x=="someotherstring")
Rob Fonseca-Ensor
Minor detail: in C# 3.0 you can shorten the syntax a little bit more by omitting the type of the array (it will be inferred). i.e. : `if( new []{s1,s2,s3,s4}.Contains("s"))`
Romain Verdier
A: 

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 );
Benoît
+6  A: 

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
}
Romain Verdier
+1  A: 

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

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