0

I would like to be able to compare multiple strings with each other and return true if they are all equal. If any of the strings equal "N/A" then they are to be ignored in the comparison. For example:

string1 = "hi";
string2 = "hi";
string3 = "hi";
string4 = "N/A";

would return true, but:

string1 = "hi";
string2 = "hey";
string3 = "hi";
string4 = "hi";

would return false.

Thanks for your help.

1
  • What code are you using to compare? Commented Dec 3, 2012 at 23:05

3 Answers 3

6
if (myStrings.Where(s => s != "N/A").Distinct().Count() > 1)
Sign up to request clarification or add additional context in comments.

4 Comments

Suggestion: Use Any() instead of Count().
Tried this but I can't get it to return false when one of the strings is different
@BrianRasmussen: Normally i would agree, but how would you apply the same logic with an Any? Distinct returns unique strings so Any would always return true.
@TimSchmelter: .Skip(1).Any()
3

Assuming that you've stored the strings in a colllection like array or list, you can use Enumerable.All:

string first = strings.FirstOrDefault(s => s != "N/A");
bool allEqual = first == null ||  strings.All(s => s == "N/A" || s == first);

Explanation: you can compare all strings with one of your choice(i take the first), if one is different allEqual must be false. I need to use FirstOrDefault since it's possible that all strings are "N/A" or the list is empty, then First would throw an exception.

DEMO

Comments

0

The question is already answered but I figured I'll state the most obvious code to do this:

bool notEqual = false;
for (int i = 0; i < list.Count - 1; i++) {
   for (int j = i + 1; j < list.Count; j++) {
      if (!(list[i].Equals(list[j])) {
         notEqual = true;
         break;
      }
   }
}

The idea is fairly simple. With the first element, you have to look at the next (length - 1) elements. However, with the second element, you've already compared it to the first, so you look at the next (length - 2) elements. You end at length - 1 because at that point you'd compare the 2nd last and the last element, which is the final possible comparison.

By all means the above answers are far more concise/elegant. This is just to show you what's actually happening on the most rudimentary level C#-wise.

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.