Reputation: 197
Well,
int a = 20;
int b = 30;
int c = 40;
int d = 50;
if (a > b,c,d)
how would i approach this, i have no idea i fail at every turn, its been hours
Upvotes: 0
Views: 3061
Reputation: 1592
If all you want to know is if the number x is greater than the other numbers, you could either compare them explicitly like if(x>b & b>c)
or use something like if(list.All(x=> a > x))
as mentioned above. If you have many numbers and all you want is the higher number, you could sort the list using a quick sort that could be efficient and get the first item.
It's a bit different if you need to compare them and get different comparissons then probably the easiest thing is to loop through the list.
Upvotes: 1
Reputation: 20332
Non-LINQ example:
if (Math.Max(a, Math.Max(b, Math.Max(c, d))) == a)
{
}
Upvotes: 1
Reputation: 50712
Put them all in a list and do this:
if(list.All(x=> a > x))
Or in one line:
if(new List<int>{a, b, c, d}.All(x=> a > x))
EDIT
I changed the Max()
to All(x => a > x)
because the a > x will not return a true when a == x
whereas Max() will do that.
Upvotes: 3
Reputation: 52411
If there is a short quantity of numbers, you can simply use the boolean logic:
if (a > b && a > c && a > d)
{
}
If you don't know in advance the quantity of numbers, what about creating a collection and compare the first number to the numbers from the collection through a loop?
var numbers = { 30, 40, 50 };
if (!numbers.Any(c => 20 <= c))
{
}
Upvotes: 7
Reputation: 245509
You can put them in an array:
int a = 20;
int[] others = { 30, 40, 50 };
if(others.All(o => a > o))
{
// do something
}
Upvotes: 5