Home >Backend Development >C++ >How to Perform a Full Outer Join on Two Lists Using LINQ?
Question:
How to use Linq to perform a full external connection on the two object lists, even if some objects in the list exist?
Explanation:
Internal connection: Elements with corresponding keys in the two lists are eliminated to exclude elements without corresponding elements.
Two lists A and B to be connected.
The key Selectkeya and Selectkeyb, specify which attribute application of the objects in A and B as the connection key.
<code class="language-csharp">internal static IEnumerable<TResult> FullOuterJoin<TA, TB, TKey, TResult>( this IEnumerable<TA> a, IEnumerable<TB> b, Func<TA, TKey> selectKeyA, Func<TB, TKey> selectKeyB, Func<TA, TB, TKey, TResult> projection, TA defaultA = default(TA), TB defaultB = default(TB), IEqualityComparer<TKey> cmp = null) { cmp = cmp ?? EqualityComparer<TKey>.Default; var alookup = a.ToLookup(selectKeyA, cmp); var blookup = b.ToLookup(selectKeyB, cmp); var keys = new HashSet<TKey>(alookup.Select(p => p.Key), cmp); keys.UnionWith(blookup.Select(p => p.Key)); var join = from key in keys from xa in alookup[key].DefaultIfEmpty(defaultA) from xb in blookup[key].DefaultIfEmpty(defaultB) select projection(xa, xb, key); return join; }</code>Project function project, specify how to convert the connected element into the result type Tresult.
The optional default value DefaultA and DefaultB, if there is no corresponding element in another list, use these values.
The above is the detailed content of How to Perform a Full Outer Join on Two Lists Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!