有時候我們想實現 leftJoin 但是 Linq 提供的 Join 相當於是 `INNER JOIN`,於是就打算實現一個 `LeftJoin` 的擴展。 ...
LinqMethod 實現 LeftJoin
Intro
有時候我們想實現 leftJoin 但是 Linq 提供的 Join 相當於是 INNER JOIN
,於是就打算實現一個 LeftJoin
的擴展。
如果要使用到左連接,你需要使用 DefaultIfEmpty 來在沒有join到數據的時候返回預設的集合
Solution
/// <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 差不多,下麵來展示一個示例:
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());
輸出:
[{"PostId":1,"PostTitle":"12333","Tag":"HHH"},{"PostId":2,"PostTitle":"12333"}]
Memo
這是使用 LinqMethod 實現 LeftJoin,如果要使用 linq 查詢語法實現左連接請參考這篇文章