[英]Throwing exceptions with Linq
I am joining 2 in memory collections 我加入了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
};
However, ideally if one of the elements can't be found, I'd like to raise an exception, something akin to 但是,理想情况下,如果找不到其中一个元素,我想提出异常,类似于
throw new System.Exception(el.Value + " cannot be found in cache!");
I was looking at the System.Interactive which offers a Catch extension method but I am unsure how to reference the current 'el' in that context. 我正在查看System.Interactive,它提供了Catch扩展方法,但我不确定如何在该上下文中引用当前的'el'。 So for example I was wondering about something like
所以例如我想知道类似的东西
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();
but, istm, that that would entail passing the whole set into the extension method rather than raising the exception when the missing value is encountered. 但是,istm,这需要将整个集合传递给扩展方法,而不是在遇到缺失值时引发异常。
Alternatively, I could replace the DefaultIfEmpty with a ThrowIfEmpty 或者,我可以用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
});
Is there a 'proper'/better way to do this? 有没有“适当的”/更好的方法来做到这一点?
You can use GroupJoin. 您可以使用GroupJoin。 Something like this should work for you:
这样的事情对你有用:
elements.GroupJoin(Cached.Elements(), e => e.Value, d => d.Name, (e, dSeq) => {
var d = dSeq.Single();
return new { e, d };
});
The GroupJoin resultSelector accepts two arguments: the left key, and the sequence of matching right keys. GroupJoin resultSelector接受两个参数:左键和匹配右键的序列。 You can raise an exception if the sequence is empty;
如果序列为空,则可以引发异常; one way to achieve that would be to use the Single operator.
实现这一目标的一种方法是使用Single运算符。
I think this is one of the places where you can use Composite Keys . 我认为这是你可以使用复合键的地方之一。
if you use equals
keyword to execute equality on join. 如果使用
equals
关键字在连接上执行相等性。
from documentation : 来自文件:
You create a composite key as an anonymous type or named typed with the values that you want to compare.
您可以将复合键创建为匿名类型,也可以使用要比较的值键入命名。 If the query variable will be passed across method boundaries, use a named type that overrides Equals and GetHashCode for the key
如果查询变量将跨方法边界传递,请使用覆盖Equals和GetHashCode的命名类型作为键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.