Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Multiple String Comparision with Same Value

Tags:

string

c#

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

like image 576
Paresh Rathod Avatar asked Dec 26 '09 07:12

Paresh Rathod


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


2 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 like this:

if ("some string".In(string1, string2, string3, string4))
{
    // Do something
}
like image 69
Romain Verdier Avatar answered Oct 02 '22 21:10

Romain Verdier


For your case you can try something like this

if (new string[] { string1, string2, string3, string4 }.Contains("someotherstring"))
{
}
like image 23
Adriaan Stander Avatar answered Oct 02 '22 22:10

Adriaan Stander