Change long if statement to LINQ
I wrote this check in C# to perform some value checking:
if ((x <= 20 && y <= 5) || (x <= 30 && y <= 10) ||
(x <= 50 && y <= 15) || (x <= 70 && y <= 20) ||
(x <= 70 && y <= 30))
{
// do something
}
I'm in the process to learn LINQ, and I would like to change the above code to use LINQ,
If you submit a code, can you ple开发者_如何学运维ase add some comment to explain the conversion.
If you really wanted to use LINQ, one way would be to store a collection of tuples that represented each of the cases (upper-bounds) and then use the Enumerable.Any
method to test if an (x, y)
pair met any of the possible conditions.
Example (in reality, you can create the collection once and give it longer lifetime, perhaps through a field-reference):
var bounds = new Dictionary<int, int>
{
{20, 5},
{30, 10},
{50, 15},
{70, 20},
{70, 30}
}.Select(kvp => new { XUpperBound = kvp.Key, YUpperBound = kvp.Value });
if (bounds.Any(tuple => x <= tuple.XUpperBound && y <= tuple.YUpperBound))
{
...
}
LINQ doesn't have anything to do with the code that you've posted. Since the numbers you've chosen seem to be largely arbitrary, I don't see a way of reducing that statement any further.
To make it look better, just format the code:
if (
(x <= 20 && y <= 5) ||
(x <= 30 && y <= 10) ||
(x <= 50 && y <= 15) ||
(x <= 70 && y <= 20) ||
(x <= 70 && y <= 30)
)
{
// do something
}
This should make your pairs clear, make it easy to add conditions, while not adding the overhead of LINQ just for the sake of using it.
精彩评论