Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Linq抛出异常_C#_Linq_Exception - Fatal编程技术网

C# 使用Linq抛出异常

C# 使用Linq抛出异常,c#,linq,exception,C#,Linq,Exception,我将加入2个内存集合 var items = from el in elements join def in Cached.Elements() on el.Value equals def.Name into temp1 from res in temp1.DefaultIfEmpty() select new { el.NodeType, res.D

我将加入2个内存集合

var items = 
    from el in elements 
    join def in Cached.Elements() 
        on el.Value equals def.Name into temp1
    from res in temp1.DefaultIfEmpty()                        
    select new
    {
        el.NodeType, 
        res.DefKey, 
        res.DefType, 
        res.BaseKey, 
        el.Value 
    };
然而,理想情况下,如果其中一个元素找不到,我想提出一个异常,类似于

throw new System.Exception(el.Value + " cannot be found in cache!");
我正在查看System.Interactive,它提供了一种捕获扩展方法,但我不确定如何在该上下文中引用当前的“el”。比如说,我想知道

    var items = (
        from el in elements 
        join def in Cached.Elements() 
            on el.Value equals def.Name into temp1
        from res in temp1.DefaultIfEmpty()                        
        select new 
        { 
            el.NodeType, 
            res.DefKey, 
            res.DefType, 
            res.BaseKey, 
            el.Value 
        })
        .ThrowIfEmpty();
但是,istm指出,这需要将整个集合传递到扩展方法中,而不是在遇到缺少的值时引发异常

或者,我可以用ThrowIfEmpty替换DefaultIfEmpty

    var items = (
        from el in elements 
        join def in Cached.Elements() 
            on el.Value equals def.Name into temp1
        from res in temp1.ThrowIfEmpty()                        
        select new 
        { 
            el.NodeType, 
            res.DefKey, 
            res.DefType, 
            res.BaseKey, 
            el.Value 
        });

有没有“合适的”或更好的方法来实现这一点?

您可以使用GroupJoin。像这样的东西应该适合你:

elements.GroupJoin(Cached.Elements(), e => e.Value, d => d.Name, (e, dSeq) => {
    var d = dSeq.Single();
    return new { e, d };
});

GroupJoin resultSelector接受两个参数:左键和匹配的右键序列。如果序列为空,则可以引发异常;实现这一点的一种方法是使用单一操作符。

我认为这是可以使用的地方之一

如果使用
equals
关键字在连接时执行相等

从文件:

将复合键创建为匿名类型或命名类型 要比较的值。如果查询变量 通过方法边界,使用重写的命名类型 键的Equals和GetHashCode


非常感谢。好球。进一步的问题。。。我认为您应该在try-catch中包装linq语句,而不是在fluent接口的上下文中抛出异常(FWIW,我对此没有任何疑虑,只是想检查一下)?对不起。。。好啊硬币掉了!从lambda中抛出异常。