c# - 来自 LINQ Select 的自定义异常?
问题描述
我Select
用来识别列表 B 中与列表 A 的元素相对应的元素。我要求列表 A 中的每个项目在列表 B 中都有对应的元素。如果不满足此要求,我想抛出一个异常,其中包括关于 A 中不匹配的元素的信息。
这就是我想出的。除了编写扩展方法之外,还有更简洁的方法吗?
var selected = listA.Select(a =>
{
var b = listB.FirstOrDefault(o => /* test correspondence with a */);
if(b == null)
{
/* throw exception with information about a */
}
return b;
}
解决方案
如果对 to 进行外连接listB
,listA
则可以找到 B 中缺少的任何元素并报告相应的 A 元素。
var temp = from a in listA
join b in listB on a.AID equals b.AID into outerB
from b in outerB.DefaultIfEmpty()
select new { a, b };
var firstUnmatched = temp.FirstOrDefault(t => t.b is null);
if (firstUnmatched != null)
{
// use firstUnmatched.a to indicate which one doesn't match in B
throw new Exception(/* ... */);
}
var allUnmatchedA = (from t in temp
where t.b is null
select t.a).ToList();
使用allUnmatchedA
上面的方法,您可以使用完整的对象列表创建一个异常,或者从中获取 ID 并仅报告这些。
推荐阅读
- javascript - Bootstrap 4 库 bootstrap.js 和 bootstrap 下拉列表互斥
- oracle - Oracle 缺少 initSID.ora
- python - 如何从 Falcon 的 POST 请求中读取原始 json 请求
- java - 使用 Array.sort 和 Lambda 表达式按降序对对象进行排序
- python - 如何创建一个在每个插槽中具有可变长度时间向量的数据帧?
- azure - zip deloy 后,azure app 服务没有任何功能
- mysql - 我需要计算每个员工每月的平均产量
- laravel - 数据排序问题,sortBy函数
- python - 如何使用 spaCy 处理 python 生成器的异常
- html - 重定向 301 不适用于 .html 页面