Question

Hi I have 4 strings.

string a,b,c, d;

I want to compare all of them. How I can I do it easily.

bool ret=true;

if(a==b) {ret=false;}
if(a==c) {ret=false;}
if(a==d) {ret=false;}
if(b==c) {ret=false;}
if(b==d) {ret=false;}
if(c==d) {ret=false;}
....
...
...

Thanks

Était-ce utile?

La solution

If you're looking for something that checks if any two elements are equal, you can create a set and check if the number of elements in the set is equal to the number of elements that were input.

string[] stringArray = new string[] {a, b, c, d};
HashSet<string> set = new HashSet<string>(stringArray);

ret = set.Count == stringArray.Length;

Autres conseils

Maybe this works?

if (a==b==c==d)

or

if (a==b && b==c && c==d)
var strings = new[] { a, b, c, d }; 
if (strings.Distinct ().Count() > 1) 
{
    //do something
}

May be you can put it in array and

string[] a = new string[4] { "a", "b", "d", "d" };
string result = a.Where(x => a.Count(z => z == x) > 1).FirstOrDefault();
if (!string.IsNullOrEmpty(result))
{
    ret = false;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top