I have two lists of the following values.
PirateShipList1
Date | PirateShipName | CrewMembers
---------------------------------------------
1/1/1800 | Cindy | 5
1/2/1800 | TheIvan | 20
1/3/1800 | TheTerrible | 10
And PirateShipList2
Date | PirateShipName | CrewMembers
---------------------------------------------
1/1/1800 | Cindy | 0
1/2/1800 | Cindy | 0
1/3/1800 | Cindy | 0
1/1/1800 | TheIvan | 0
1/2/1800 | TheIvan | 0
1/3/1800 | TheIvan | 0
1/1/1800 | TheTerrible | 0
1/2/1800 | TheTerrible | 0
1/3/1800 | TheTerrible | 0
I want to merge the two lists on Date and PirateShipName so that if It's present in List1, I take its CrewMembers value, else I take Lists 2 CrewMembers value.
Thus the final list would look like.
Date | PirateShipName | CrewMembers
---------------------------------------------
1/1/1800 | Cindy | 5
1/2/1800 | Cindy | 0
1/3/1800 | Cindy | 0
1/1/1800 | TheIvan | 0
1/2/1800 | TheIvan | 20
1/3/1800 | TheIvan | 0
1/1/1800 | TheTerrible | 0
1/2/1800 | TheTerrible | 0
1/3/1800 | TheTerrible | 10
I've found I can do this hackily by the following
List<PirateLedgers> Final = PirateShipList2.Union(PirateShipList1)
.GroupBy(x => new { x.Date, x.PirateShipName })
.Select(x => new PirateLedgers
{
Date = x.Key.Date,
PirateShipName = x.Key.PirateShipName,
CrewMembers = x.Sum(l => l.CrewMembers)
}).ToList<PirateLedgers>();
But I suspect that there is a smarter and better way of doing this with an actual join. Thank you in advance either way!