1

Is there a way to compare two strings to another string at once?

Example:

string1 == string2 && string3;

(I know this isn't the way, just a representation of what I mean)

13
  • & or &&? stackoverflow.com/questions/35301 Commented Mar 18, 2014 at 15:44
  • 2
    & looks like the VB.NET concatenation operator. Is that intended? Commented Mar 18, 2014 at 15:44
  • 3
    string1 == string2 == string3 ?? Commented Mar 18, 2014 at 15:45
  • @Bolu, wow...... remove it. Commented Mar 18, 2014 at 15:45
  • 1
    @Bolu (string1 == string2) is bool then (bool) == string3. Commented Mar 18, 2014 at 15:47

3 Answers 3

8

Generally, no, there is no way to do this that resembles the way you asked to do it.

However, if the strings to compare with are in a collection of some kind, you can do this:

 if (stringCollection.All(s => s == string1) )
Sign up to request clarification or add additional context in comments.

5 Comments

That or if (stringCollection.Any(s => s == string1) ). All returns true if all elements match. Any returns true if one or more elements match
Sorry just want to clarify, is that comparing all the strings in the collection to one another, or just one to all the others?
@Callum It compares one to all the others... but since you used an AND operator, it should match what your pseudocode was looking for here.
@Callum: the portion (s => s... refers to your other strings, string2 and 3 which should be in a collection
@JoelCoehoorn Yeah that's what I was after, but since they aren't already in a collection it will probably be easier to just do two comparisons. Thanks anyway!
0

If you don't want to deal with putting your values into a collection or list, you could do an extension method like this:

static class extensions
{
    private static bool InSet(this string s, params string[] p )
    {
        return p.Contains(s);
    }
}

Then when you want to test if a string matches a value in a set you can do this:

if (String1.InSet(String2, String3))
{
    // do something.
}

1 Comment

I would like to add, that this solution works with any number of parameters.
0

Besides Linq's All method, you can do also with List methods, like TrueForAll

    string searchString = "hi";
    var listStrings = new List<string>() { "hi", "there" };
    bool allOfThem = listStrings.TrueForAll(x => x == searchString);
    bool atLeastOne = listStrings.Contains(searchString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.