c# - 如何对长 LINQ 链中可枚举的每一项进行断言

标签 c# linq assert

有没有类似的东西

myList.Select(..).Where(...).Assert(x=>x.Length<2).Select(...)...

如果任何项目不满足条件,它会抛出,否则会像 .Select(x=>x) 一样?

最佳答案

您可以很容易地自己编写这个扩展。假设您有一个异常,比如 AssertionFailedException,这样的事情就可以解决问题。

public static IEnumerable<T> Assert<T>(this IEnumerable<T> items, Func<T, bool> expression)
{
    foreach(var item in items)
    {
          if(!expression(item))
                throw new AssertionFailedException();
          yield return item;
    }
}

关于c# - 如何对长 LINQ 链中可枚举的每一项进行断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58957427/

相关文章:

c# - 使用 Entity Framework 时为 Select() 创建通用选择器

c++ - 迭代器的验证

c++ - std::assert 发生了什么

c# - 使用 ASP.NET MVC 发送 500 封电子邮件 : throttling

c# - Dispatcher' 不包含 'InvokeAsync' 的定义并且没有扩展方法 'InvokeAsync'

c# - 在 C# 中使用 `using` 关键字避免多次处置的最佳实践

c# - 查询嵌套列表

C# - LINQ Select() 调用函数两次

c# - 是否存在为歧义语句返回解析林的 C# 解析器生成器?

C++ 与 Dll 通信出错