Reputation: 1678
I am familiar with Multiple conditions in ternary conditional operator like this:
( condition A ? value A :
( condition B ? value B :
( condition C ? value C :
...
)
)
)
but I cannot understand how the code below works (function suppose to return an integer:
return (co1.Nr() < co2.Nr() ? -1 :
( co1.Nr() == co2.Nr() ? (co1.Id() < co2.Id() ? -1 :
(co1.Id() == co2.Id() ? 0 : 1)) : 1;
Will you please explain me?
Upvotes: 1
Views: 127
Reputation: 172
Basically this is what the code does with if's statements
if (co1.Nr()< co2.Nr()){
return -1;
}else if (co1.Nr()==co2.Nr()){
if (co1.Id() <co2.Id()){
return -1;
}else if( co1.Id() == co2.Id()){
return 0;
}else{
return 1;
}
}else
{
return 1;
}
Upvotes: 0
Reputation:
The condition map to following
if(co1.Nr() < co2.Nr())
return -1;
else if(co1.Nr() == co2.Nr())
if(co1.Id() < co2.Id())
return -1;
else if(co1.Id() == co2.Id())
return 0;
else
return 1;
else
return 1;
Upvotes: 1
Reputation: 121998
Break it and understand. For ex: Consider the first part.
return (co1.Nr() < co2.Nr() ? -1 : (all_other_codes);
If the condition co1.Nr() < co2.Nr()
true rerutn -1 else execute all_other_codes
. Where as all_other_codes
returns another integer
.
Now look at all_other_codes
( co1.Nr() == co2.Nr() ? (co1.Id() < co2.Id() ? -1 :
(co1.Id() == co2.Id() ? 0 : 1)) : 1;
If co1.Nr() == co2.Nr()
true return the value of
(co1.Id() < co2.Id() ? -1 :
(co1.Id() == co2.Id() ? 0 : 1))
else return 1
.
Upvotes: 3
Reputation: 2084
if co1.Nr() < co2.Nr() return -1
else if co1.Nr() == co2.Nr() then
if co1.Id() < co2.Id() return -1
else if co1.Id() == co2.Id() return 0
else return 1
else return 1
Upvotes: 1
Reputation: 878
That's a primary and secondary sort: order by Nr, and if they're equal, order by Id. Returning -1, 0, and 1 is standard for comparison tests used for sorting.
Upvotes: 2