Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Edit:</strong> Fixed up. This is sloppy but it should work.</p> <pre><code> listA //Start with lisA .Where(a=&gt;!listB.Any(b=&gt;a.Key == b.Key)) // Remove any that are duplicated in listB .Select(a =&gt; new TypeAB() { Key=a.Key, ValueA=a.Value}) // Map each A to an AB .Union( listB.Select(b =&gt; { var correspondingA = listA.FirstOrDefault(a =&gt; a.Key == b.Key); //Is there an a that corresponds? return new TypeAB() { Key=b.Key, ValueB=b.Value, //Value B is easy ValueA= correspondingA!=null ? (int?)correspondingA.Value : null //If there is an A than map its value }; }) ) </code></pre> <p>As an aside, if you're using this as some sort of domain operation, TypeA and TypeB should probably be based on some sort AorBIsAConceptThatHasMeaningInTheDomain base class. That's just a general rule whenever you find yourself combining lists. If no such concept exists, then you probably don't need to be combining the lists.</p> <p>On the other hand, if you're doing this as part of a mapping - such as mapping domain objects to UI - you might be able to simplify your code somewhat by using anonymous types instead of a TypeAB class. (Or maybe not, this one is up to personal preference)</p> <p><strong>Edit Edit</strong> Here's a slightly more intellectually interesting answer using hashes</p> <pre><code> var listAB = listA.Cast&lt;object&gt;().Union(listB.Cast&lt;object&gt;()).ToLookup(x =&gt; x is TypeA ? (x as TypeA).Key : (x as TypeB).Key) .Select(kv =&gt; { var a = kv.FirstOrDefault(x =&gt; x is TypeA) as TypeA; var b = kv.FirstOrDefault(x =&gt; x is TypeB) as TypeB; return new TypeAB() { Key = kv.Key, ValueA = a != null ? (int?)a.Value : null, ValueB = b != null ? (int?)b.Value : null }; }).ToList(); </code></pre>
 

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