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

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

    Another way to do it would be:

    //Step 1: Merge the lists while selecting the matching objects from rightList using Last()
    var mergedList = leftList.Concat(rightList)
     .GroupBy(x => x.Id)
     .Select(x => x.Last());
    
    //Step 2: Do a inner join between mergedList and leftList to get a left join result as originally required.
    var innerJoinQuery = from mPerson in mergedList
                         join leftPerson in leftList on mPerson.Id equals leftPerson.Id
                         select new { Id = leftPerson.Id, Name = mPerson.Name, Changed = mPerson.Changed };
    

提交回复
热议问题