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 查询语法实现左连接请参考这篇文章