سؤال

I have two variable spn and fmi.

(3064,11),(3064,14),(3064,16),(123,11)

spn gets the first values(3064,3064,3064,123) and fmi gets (11,14,16,11)

and here is the code :

    if ((Spn != 3064) && (Fmi != 11) || (Fmi != 16))
    {
        Console.WriteLine("Spn:{0}  Fmi:{1}   Added", Spn, Fmi);
    }
    else
    {
        Console.WriteLine("Spn:{0}  Fmi:{1}   skipped", Spn, Fmi);
    }

So I want the output to show :

(3064,14) added
(123,11) added
(3064,16) skipped
(3064,11) skipped

the above code is wrong and this one is the correct one :

 if ((Spn != 3064) || (Fmi != 11) && (Fmi != 16))

I really don't get it. it is exactly opposite of what I wrote before and expected to be correct! can anybody help ?

هل كانت مفيدة؟

المحلول 2

Based on your example output it sounds like you want to add an item to the list if:

  • Spn is not 3064 OR IF
  • Fmi is something other than 11 or 16

Translating those two parts into code, we get:

Spn is not 3064

Spn != 3064


Fmi is something other than 11 or 16

or expressed another way,

Fmi is not 11 and Fmi is not 16

 Fmi != 11 && Fmi != 16


Now putting those two together using the OR in my bulleted list above, you get:

Spn != 3064 || (Fmi != 11 && Fmi != 16)


And we can optionally remove the parentheses because && has a higher precedence than ||:

Spn != 3064 || Fmi != 11 && Fmi != 16

And this is exactly the expression that you yourself found to work.


It might be easier to put everything in terms of what you want to skip rather than what to add. In other words,

Skip a pair if:

  • Spn is 3064 AND
  • Fmi is 11 or 16

So

Spn == 3064 && (Fmi = 11 || Fmi == 16)

(the parentheses are necessary this time)

if (Spn == 3064 && (Fmi = 11 || Fmi == 16))
{
    Console.WriteLine("Spn:{0}  Fmi:{1}   skipped", Spn, Fmi);
}
else
{
    Console.WriteLine("Spn:{0}  Fmi:{1}   Added", Spn, Fmi);
}

نصائح أخرى

This happens because of operator precedence in C#.

&& has higher precedence than || and is evaluated first.

In your correct version, it evaluates (Fmi != 11) && (Fmi != 16) first and then the result of that OR (Spn != 3064). Only (3064,14) and (123,11) match.

In your incorrect version (Spn != 3064) && (Fmi != 11) is evaluated first and the result of that is applied to OR (Fmi != 16). This is a match for (3064,14), (3064,16) and (123,11).


The rules that you want the selection to happen are not really clear to me so please decide yourself, applying the answer given.

If you want to enforce some order of precedence, you can put some groups into parentheses ( ), e.g.

(A || B) && C

OR will be evaluated before AND.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top