Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two lists based on a property?

Tags:

c#

list

linq

I have two lists, one fake and one real, like:

BEFORE

// fake (list 1)
{ ID = 1, Year = 2011, X = "" }
, { ID = 2, Year = 2012, X = "" }
, { ID = 3, Year = 2013, X = "" }

// real (list 2)
{ ID = 35, Year = 2011, X = "Information" }
, { ID = 77, Year = 2013, X = "Important" }

I want to merge them looking for the Year, the result should be:

AFTER

{ ID = 35, Year = 2011, X = "Information" }
, { ID = 2, Year = 2012, X = "" }
, { ID = 77, Year = 2013, X = "Important" }

It must remove elements with the same year on the first list and add the element with the equivalent Year on the second list to the first list, keeping the order.

How can I do it using Linq?

like image 862
BrunoLM Avatar asked Oct 11 '11 19:10

BrunoLM


1 Answers

You should be able to do that using a "left join":

from f in fake
join r in real
on f.Year equals r.Year
into joinResult
from r in joinResult.DefaultIfEmpty()
select new
       {
           ID = r == null ? f.ID : r.ID,
           Year = f.Year,
           X = r == null ? f.X : r.X
       };
like image 187
Justin Niessner Avatar answered Oct 19 '22 09:10

Justin Niessner