Search code examples
.netlinqc#-4.0list-manipulation

Merging lists of objects using linq while showing preference over a condition in one list


I have a class called Content which contains some properties

One of the properties is the CultureCode.

List A contains all the "en" Content classes List B contains all the "en-GB" Content classes

I want to merge them so that: we get only the "en" Content in the final list but whenever there is a match in en-GB over a condition to include that item in the final list instead of en.

So if:

List A

en - 1
en - 2
en - 3
en - 4
en - 5

List B

en-GB - 2
en-GB - 4
en-GB - 6

then

Mixed List

en - 1
en-GB - 2
en - 3
en-GB - 4
en - 5

I have tried something like this:

IEnumerable<Content> mixed = from x in listA
join y in listB on new {x.Property1, x.Property2, x.Property3} equals
    new {y.Property1, y.Property2, y.Property3} into g
from o in g.DefaultIfEmpty(new Content()
{
    Id = x.Id,
    CultureCode = x.CultureCode,
    Property1 = x.Property1,...
})
where
(
    ...
)
select new Content()
{
    Id = o.Id,
    CultureCode = o.CultureCode,
    Property1 = o.Property1,
    Property2 = o.Property2,
    Property3 = o.Property3,
};

And multiple variations of that but the result is never quite exactly right.

Any ideas?


Solution

  • Something along the lines of this would do it:

    var result = (from a in listA
                  join b in listB on a.Property1 equals b.Property1 into g
                  from j in g.DefaultIfEmpty()
                  select new Content() { 
                       // Favour listA's culture code
                       CultureCode = j == null ? a.CultureCode : j.CultureCode, 
                       Property1 = a.Property1 
                  });
    

    And a live example to demonstrate: http://rextester.com/AAWQ92029