LinqMethod 實現 LeftJoin

LinqMethod 實現 LeftJoin

Intro

有時候咱們想實現 leftJoin 可是 Linq 提供的 Join 至關因而 INNER JOIN,因而就打算實現一個 LeftJoin 的擴展。
若是要使用到左鏈接,你須要使用 DefaultIfEmpty 來在沒有join到數據的時候返回默認的集合git

Solution

源代碼:https://github.com/WeihanLi/WeihanLi.Common/blob/dev/src/WeihanLi.Common/Extensions/EnumerableExtension.cs#L149github

/// <summary>
/// LeftJoin extension
/// </summary>
/// <typeparam name="TOuter">outer</typeparam>
/// <typeparam name="TInner">inner</typeparam>
/// <typeparam name="TKey">TKey</typeparam>
/// <typeparam name="TResult">TResult</typeparam>
/// <param name="outer">outer collection</param>
/// <param name="inner">inner collection</param>
/// <param name="outerKeySelector">outerKeySelector</param>
/// <param name="innerKeySelector">innerKeySelector</param>
/// <param name="resultSelector">resultSelector</param>
/// <returns></returns>
public static IEnumerable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer,
    IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector,
    Func<TOuter, TInner, TResult> resultSelector)
{
    return outer
        .GroupJoin(inner, outerKeySelector, innerKeySelector, (outerObj, inners) => new
        {
            outerObj,
            inners = inners.DefaultIfEmpty()
        })
        .SelectMany(a => a.inners.Select(innerObj => resultSelector(a.outerObj, innerObj)));
}

Use

使用起來和 Join 差很少,下面來展現一個示例post

var posts = new[] { new { PostId = 1, PostTitle = "12333", }, new { PostId = 2, PostTitle = "12333", }, };
var postTags = new[] { new { PostId = 1, Tag = "HHH" } };

var result = posts.LeftJoin(postTags, p => p.PostId, pt => pt.PostId, (p, pt) => new { p.PostId, p.PostTitle, pt?.Tag }).ToArray();
Console.WriteLine(result.ToJson());

輸出:this

[{"PostId":1,"PostTitle":"12333","Tag":"HHH"},{"PostId":2,"PostTitle":"12333"}]

Memo

這是使用 LinqMethod 實現 LeftJoin,若是要使用 linq 查詢語法實現左鏈接請參考這篇文章code

Reference

相關文章
相關標籤/搜索