C # Comparing multiple lines at the same cost

Please take a look at the case below, of course, which will be interesting.

if I want to assign the same value to multiple objects, I will use something like this

string1 = string2 = string3 = string 4 = "some string"; 

Now, what I want to do, I want to compare strings string1, string2, string3 and string4 with "someotherstring" ... questions - is there any way to do this without writing a separate comparison. those.

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

Hope I could explain the question .. kindly provided me with help on this.

Regards, Paresh Ratod

+4
source share
6 answers

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 as follows:

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

In your case, you can try something like this

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

I find LINQ very expressive and will consider its use for this problem:

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

No, in C # no, but you can write it like this:

  (string1 == string2 && string2 == string3 && string3 == string4 && string4 == "someotherstring") 
+3
source

You can create a function to make code easier to read:

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

If you want to compare this list of strings with consecutive "other strings", you might need to create a list object "myStringList" in which you would add string1 / 2/3/4, then define a function that will be available to write

 compare( "someotherthing", myStringList ); 
+1
source

I donโ€™t believe that. How do you know which of them did not compare or did not match. It would not be possible to evaluate the side effect of such a comparison.

0
source

All Articles