c# - 如果交换逻辑,具有三元运算的 LINQ 运算会导致测试失败

标签 c# linq

所以我使用 LINQ 来评估字符串并使用 Regex 库来解析数字字符串或任何其他字符返回 0。如果我交换逻辑,它应该仍然可以以任何一种方式工作,但它不... 下面是这两种情况的示例。

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();

最佳答案

问题是您实际上并没有在第二行代码中交换逻辑。要完全交换逻辑,您需要像这样否定 if 语句:

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

Regex.IsMatch(d, @"[^\d-]")) 之前添加 ! 将为您提供所有非有效数字并返回值为 0。

关于c# - 如果交换逻辑,具有三元运算的 LINQ 运算会导致测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46489530/

相关文章:

c# - 是创建自定义异常还是等待下线发生 NullReferenceException?

c# - 将许多 TimeSpans 减少为更少的平均 TimeSpans 的干净方法?

entity-framework - 实现排序属性的最佳实践

c# - 如何在 C#.NET 中不同类型的对象之间进行深度复制

c# - 使用属性上的总和验证集合

c# - 基于列内容和标题的 ListView AutoResizeColumns

c# - MVC3 : Overriding the Model values in HTTPPost action method

c# - 一种将字符串排序为另一个字符串的更简洁的方法

c# - 如果给定父元素下存在某个元素,则仅解析 xml 文件

c# - 在使用LINQ语句添加指示值源的元数据时,如何合并两个列表?