简体   繁体   中英

If you have multiple variables with different values and i want to pass these values through a block of code that process the value,how do i do that?

This is a hypothetical scenario, but lets say that

int age1 = 12, age2=3, age3=7

I want to pass each of these variable to through a block of code that tells me whether or not it the age is greater then 10.

Is there a way to do that without loops and writing a whole bunch of if statements. (If I have to write 1 if statement that is fine, but not multiple ones)

As a generalized solution, you can try params and Linq ( Any ):

 static bool HasGreaterThan10(params int[] ages) {
   return ages.Any(age => age > 10);
 }

Example

if (HasGreaterThan10(12, 3, 7)) {
  ...
}

If you want to test if all the ages are greater then 10 use All :

static bool AllGreaterThan10(params int[] ages) {
   return ages.All(age => age > 10);
}

...

if (AllGreaterThan10(age1, age2, age3, age4)) {
  ...
}

You can declare the array locally and get rid of method if you want:

if (new int[] {age1, age2, age3}.Any(age => age > 10)) {
  ...
}

The concept you are looking for is called arrays .

And looping over an array is always preferred over writing code that names things a1, a2, a3, ... and that then explicitly deals with all those values.

The point is: maybe you think that those values will do today, but thing is: there is a certain chance that you will have to use 4 values tomorrow. And 7 the other week.

You can use the "or else" operator ( || )

bool isGreater(int age1,  int age2, int age3) {
  return (age1>10) || (age2>10) || (age3>10);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM