Hello,
I have an array in c# identical values in it.
But, sometimes, it can happen that one value gets mixed and then array should be considered as invalid.
Let say, I have an valid array of values: [0]=N,[1]=N,[2]=N;
And this is an example of invalid array: [0]=N,[1]=K,[2]=N;

To determine an intruder, I have one idea how to solve: (syntax is maybe wrong, ignore it)

int n=0;
int k=0;
int s=0;
int j=0;
foreach (string x in array){
if(x=="N"){ n++; }
else if (x=="K"){ k++; }
else if (x==J){ j++; }
else s++;
}

I don't have an variable to match, lets say, a variable
string array_should_be_k=K; to check if array with values match this variable.
If one value in array is N and when I check it with an array_should_be_k then array is invalid

So, one logic was - if K values are bigger than the rest of values, then Array should be K.

if (k>n || k>j || k>d || k>s && (n=0 && j=0 && d=0 && s=0)){
messagebox.show("K");
}
else if (n>k || n>j || n>d || n>s && (k=0 && j=0 && d=0 && s=0)){
messagebox.show("N");
}
else if (d>n || d>j || d>k || d>s && (n=0 && j=0 && k=0 && s=0)){
messagebox.show("D");
}
else if (s>n || s>j || s>k || s>d && (n=0 && j=0 && k=0 && d=0)){
messagebox.show("S");
}
else {
messagebox.show("Array is mixed");
}

Is there another approach in c# (without linq)?

Recommended Answers

All 3 Replies

If I understand you well, why don't you check the first element in your array and check it against the rest of the elements in a loop?
If at the end, they are all equal, you're done.

Another way would be to use a bool that goes false if there are any values you don't like:

bool correct = true
foreach (string x in array)
{
    if(x != "K")
    { 
        correct = false; 
    }
}
if(!correct)
{
    //do stuff
}

Just realized I missed a statement in my example:

bool correct = true
foreach (string x in array)
{
    if(x != "K")
    { 
        correct = false;
        break;
    }
}
if(!correct)
{
    //do stuff
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.