LEFT OUTER JOIN in LINQ

后端 未结 22 2511
臣服心动
臣服心动 2020-11-21 04:49

How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause? Corr

22条回答
  •  逝去的感伤
    2020-11-21 05:34

    Now as an extension method:

    public static class LinqExt
    {
        public static IEnumerable LeftOuterJoin(this IEnumerable left, IEnumerable right, Func leftKey, Func rightKey,
            Func result)
        {
            return left.GroupJoin(right, leftKey, rightKey, (l, r) => new { l, r })
                 .SelectMany(
                     o => o.r.DefaultIfEmpty(),
                     (l, r) => new { lft= l.l, rght = r })
                 .Select(o => result.Invoke(o.lft, o.rght));
        }
    }
    

    Use like you would normally use join:

    var contents = list.LeftOuterJoin(list2, 
                 l => l.country, 
                 r => r.name,
                (l, r) => new { count = l.Count(), l.country, l.reason, r.people })
    

    Hope this saves you some time.

提交回复
热议问题