LINQ - Full Outer Join

后端 未结 16 1585
既然无缘
既然无缘 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:23

    My clean solution for situation that key is unique in both enumerables:

     private static IEnumerable FullOuterJoin(
                IEnumerable a, IEnumerable b,
                Func key_a, Func key_b,
                Func selector)
            {
                var alookup = a.ToLookup(key_a);
                var blookup = b.ToLookup(key_b);
                var keys = new HashSet(alookup.Select(p => p.Key));
                keys.UnionWith(blookup.Select(p => p.Key));
                return keys.Select(key => selector(alookup[key].FirstOrDefault(), blookup[key].FirstOrDefault()));
            }
    

    so

        var ax = new[] {
            new { id = 1, first_name = "ali" },
            new { id = 2, first_name = "mohammad" } };
        var bx = new[] {
            new { id = 1, last_name = "rezaei" },
            new { id = 3, last_name = "kazemi" } };
    
        var list = FullOuterJoin(ax, bx, a => a.id, b => b.id, (a, b) => "f: " + a?.first_name + " l: " + b?.last_name).ToArray();
    

    outputs:

    f: ali l: rezaei
    f: mohammad l:
    f:  l: kazemi
    

提交回复
热议问题