Left join on two Lists and maintain one property from the right with Linq

前端 未结 4 721
日久生厌
日久生厌 2021-02-06 01:08

I have 2 lists of the same type. The left list:

var leftList = new List();
leftList.Add(new Person {Id = 1, Name = \"John\", Chang         


        
4条回答
  •  礼貌的吻别
    2021-02-06 01:41

    This looks like a pretty standard left outer join scenario.

    I always keep this extension method handy for left outer joins so I don't have to look up how to use the nasty query syntax (or remember wtf a GroupJoin is)...

    public static class LinqEx
    {
        public static IEnumerable LeftOuterJoin(
            this IEnumerable outer, 
            IEnumerable inner, 
            Func outerKeySelector, 
            Func innerKeySelector, 
            Func resultSelector)
        {
            return outer
                .GroupJoin(inner, outerKeySelector, innerKeySelector, (a, b) => new
                {
                    a,
                    b
                })
                .SelectMany(x => x.b.DefaultIfEmpty(), (x, b) => resultSelector(x.a, b));
        }
    }
    

    Now you can:

    leftList.LeftOuterJoin(
         rightList, 
         lft => lft.Id,
         rgt => rgt.Id,
         (lft, rgt) => new Person{Id = lft.Id, 
                                  Name = lft.Name, 
                                  Changed = rgt == null ? lft.Changed : rgt.Changed})
    

提交回复
热议问题