LINQ - Full Outer Join

后端 未结 16 1552
既然无缘
既然无缘 2020-11-21 22:45

I have a list of people\'s ID and their first name, and a list of people\'s ID and their surname. Some people don\'t have a first name and some don\'t have a surname; I\'d l

16条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 23:00

    Here is an extension method doing that:

    public static IEnumerable> FullOuterJoin(this IEnumerable leftItems, Func leftIdSelector, IEnumerable rightItems, Func rightIdSelector)
    {
        var leftOuterJoin = from left in leftItems
            join right in rightItems on leftIdSelector(left) equals rightIdSelector(right) into temp
            from right in temp.DefaultIfEmpty()
            select new { left, right };
    
        var rightOuterJoin = from right in rightItems
            join left in leftItems on rightIdSelector(right) equals leftIdSelector(left) into temp
            from left in temp.DefaultIfEmpty()
            select new { left, right };
    
        var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);
    
        return fullOuterJoin.Select(x => new KeyValuePair(x.left, x.right));
    }
    

提交回复
热议问题