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

前端 未结 4 719
日久生厌
日久生厌 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:44

    Well spender was faster then me, I did without any extension method.

    Without any extension method:

    List mergedList =  leftList
                .GroupJoin(
                    rightList, left => left.Id, right => right.Id, 
                    (x, y) => new { Left = x, Rights = y  }
                )
                .SelectMany(
                    x => x.Rights.DefaultIfEmpty(),
                    (x, y) => new Person
                    {
                        Id = x.Left.Id, 
                        Name = x.Left.Name, 
                        Changed = y == null ? x.Left.Changed : y.Changed
                    }
                ).ToList();
    

    The GroupJoin makes left outer join operation.

提交回复
热议问题