Ben Brown Ben Brown -3 years ago 129
C# Question

LINQ operation with ternary operation causing tests to fail if logic is swapped

So I am using LINQ to evaluate a string and use the Regex library to either parse a string that is a digit or any other character returns 0. If I swap the logic, it should still work either way but it doesn't... below is an example of the two scenarios.

This example is the one that allows for my tests to pass.

return Regex.Split(number, @"[^\d-]")
.Select(d => Regex.IsMatch(d, @"[\d-]") ? int.Parse(d.TrimEnd('-')) : 0)
.Where(d => d <= 1000).ToList();

Logic swapped, it should pass still, but causes a couple of my tests to fail...

return Regex.Split(number, @"[^\d-]")
.Select(d => Regex.IsMatch(d, @"[^\d-]") ? 0 : int.Parse(d.TrimEnd('-')))
.Where(d => d <= 1000).ToList();

Answer Source

The issue is that you aren't actually swapping the logic in your second line of code. To fully swap the logic, you would need to negate the if statement like so:

return Regex.Split(number, @"[^\d-]").Select(d => !Regex.IsMatch(d, @"[^\d-]") ? 0 : int.Parse(d.TrimEnd('-'))).Where(d => d <= 1000).ToList();

Adding the ! before Regex.IsMatch(d, @"[^\d-]") will give you everything that is NOT a valid digit and return a value of 0.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download