Search code examples
c#joinlinq-to-entities

How to keep original values with join operator?


I got two lists that I need to join to set a value between them. The first list is companytaxesnumber and the second is ordertaxes. Both of them got a TaxId which is used to join them.

Here the code about that :

destination.OrderTaxes = destination.OrderTaxes.
            Join(src.companytaxesnumber, vModel => vModel.TaxId, source => source.TaxId, (dest, source) =>
            {
                  dest.LegalNumber = source.LegalNumber; return dest;
            }).ToList();

My problem is if companytaxesnumber have less data then ordertaxes (for any reason), the join operator will return a result with the count of companytaxesnumber and will lost the other data of ordertaxes that it has not been able to join.

Did you know how can I make sure I got the complete ordertaxes list even if some data has not been join with companytaxesnumber?


Solution

  • You're looking for a LEFT OUTER JOIN, you can accomplish your task with:

    var result = from o in destination.OrderTaxes
                 join d in src.companytaxesnumber on o.TaxId equals d.TaxId into temp
                 from p in temp.DefaultIfEmpty()
                 select new { /* assign the fields appropriately */ };
    

    a LEFT OUTER JOIN will allow you to retain all elements on the first collection regardless of whether it has any correlated elements in the second collection.