Throwing Exceptions with Linq

I am connecting 2 in memory collections

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 cannot be found, I would like to create an exception, something similar to

 throw new System.Exception(el.Value + " cannot be found in cache!"); 

I looked at System.Interactive, which offers a Catch extension method, but I'm not sure how to reference the current "el" in this context. So, for example, I was interested in 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 this would entail passing the entire set to an extension method, rather than raising an exception when a missing value is encountered.

Alternatively, I can replace DefaultIfEmpty with ThrowIfEmpty

  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 β€œright” / best way to do this?

+4
source share
2 answers

You can use 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 }; }); 

Result GroupJoinSelector takes two arguments: the left key and the sequence of valid keys. You can throw an exception if the sequence is empty; one way to achieve this would be to use the Single operator.

+2
source

I think this is one of the places where you can use Composite Keys .

if you use the equals keyword to perform equality when combining.

from the documentation:

You create the composite key as an anonymous type or named using the value you want to compare. If the request variable is passed through the boundaries of the method, it uses a named type that overrides Equals and GetHashCode for the key

+1
source

Source: https://habr.com/ru/post/1398181/


All Articles