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)

Callum
  • 23
  • 4

3 Answers3

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) )
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • That or `if (stringCollection.Any(s => s == string1) )`. All returns true if all elements match. Any returns true if one or more elements match – Ricardo Appleton Mar 18 '14 at 15:52
  • 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 Mar 18 '14 at 15:52
  • @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. – Joel Coehoorn Mar 18 '14 at 15:55
  • @Callum: the portion `(s => s... ` refers to your other strings, string2 and 3 which should be in a collection – Ricardo Appleton Mar 18 '14 at 15:55
  • @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! – Callum Mar 18 '14 at 15:57
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);
Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74
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.
}
William Leader
  • 814
  • 6
  • 20