[英]Throwing exceptions with Linq
我加入了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,它提供了Catch扩展方法,但我不确定如何在该上下文中引用当前的'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接受两个参数:左键和匹配右键的序列。 如果序列为空,则可以引发异常; 实现这一目标的一种方法是使用Single运算符。
我认为这是你可以使用复合键的地方之一。
如果使用equals
关键字在连接上执行相等性。
来自文件:
您可以将复合键创建为匿名类型,也可以使用要比较的值键入命名。 如果查询变量将跨方法边界传递,请使用覆盖Equals和GetHashCode的命名类型作为键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.