Note that there are some explanatory texts on larger screens.

plurals
  1. POFastest, cleanest way in linq to exclude elements from other type (+ef)
    primarykey
    data
    text
    <p>Assume we have these two classes:</p> <pre><code>class GenericFoo { public Guid ID; ... } class SpecialFoo { public Guid ID; public Guid GenericFooID; ... } </code></pre> <p>GenericFoo is a kind of template class, that SpecialFoos can be created from. </p> <p>Now, I have a <code>DbSet&lt;GenericFoo&gt; g</code> and a <code>DbSet&lt;SpecialFoo&gt; s</code>. Any SpecialFoo.GenericFooID <em>may</em> exist in g, but may also be missing. (The GenericFoo may e.g. have been deleted). The opposite is true as well, of course.</p> <p>What I would like is a call to get the ones that lacks matching GenericFooID, something like:</p> <pre><code>missing = s.Except(g) </code></pre> <p>That doesn't work, since Except only works for same classes. For now I've solved this by using a rather contrived solution:</p> <pre><code>ExistingIds = g.Select(f=&gt;f.ID); missing = s.Where(f =&gt; !ExistingIds.Contains(s.GenericFooID)); </code></pre> <p>One major downside here is that we lose type safety (if someone mistype g and specifies a similar class, there would be no way to check this). I would prefer having something like an <code>IComparer&lt;type1, type2&gt;</code> so that the <code>Except</code> call would work.</p> <p>The other options I've found is </p> <ul> <li>to make a "fake left join" using group join, and just keeping the non matching</li> <li>to convert the first one into a dictionary, hash table etc. just to speed it up</li> <li>attempting to create a Generic->Special converter, and then a IComparer just for the sake of using <code>Except</code></li> </ul> <p>My questions are:</p> <ol> <li>Are there any nicer way to solve this, just talking about linq to objects?</li> <li>What is the fastest way to solve this, in the context of entity framework?</li> </ol>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload