简体   繁体   中英

Compare multiple strings in C#

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.

if (myStrings.Where(s => s != "N/A").Distinct().Count() > 1)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM