首页 > 解决方案 > 来自 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;
}

标签: c#linq

解决方案


如果对 to 进行外连接listBlistA则可以找到 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 并仅报告这些。


推荐阅读