Question:
Give two lists of personnel containing IDs and names or surnames, and perform a full external connection to generate a personal list containing names and surnames.
Answer:
The difference between the whole external connection and other connections is that it contains the items from two input lists, even if there is no matching element in another list. For this reason, we can use the extension method, and its working principle is as follows:
Use the specified key selectioner function to create a search table for two input lists.
FullOuterJoin
Identify the unique button in the two search tables and combine them into a collection.
This code will output the following results:
internal static class MyExtensions { 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, 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 let xa = alookup[key].DefaultIfEmpty(default(TA)) let xb = blookup[key].DefaultIfEmpty(default(TB)) select projection(xa.FirstOrDefault(), xb.FirstOrDefault(), key); return join; } }
This Revised Answer Uses To handle the portal null values from
More GraceFully and Directly Outputs the name and Surname, , Making The Result Clearer. Thevar ax = new[] { new { id = 1, name = "John" }, new { id = 2, name = "Sue" } }; var bx = new[] { new { id = 1, surname = "Doe" }, new { id = 3, surname = "Smith" } }; ax.FullOuterJoin(bx, a => a.id, b => b.id, (a, b, id) => new { a?.name, b?.surname, id }) .ToList().ForEach(Console.WriteLine);
Are Null.
The above is the detailed content of How to Perform a Full Outer Join in LINQ to Merge Two Lists of People Based on ID?. For more information, please follow other related articles on the PHP Chinese website!