Use DefaultIfEmpty in a LINQ query with Join

3

The purpose is to join these two lists, and if in the pr list you have an item that does not match the un list, the default value is returned. I know there are other ways, however, I'd like a solution using DefaultIfEmpty

var pr = new List<int>() { 1, 2, 3 };
var un = new List<int>() { 1, 2 };
var pu = from p in pr.DefaultIfEmpty(new int())
        join u in un on p equals u
        select p;
    foreach (var i in pu)
    {
        Console.WriteLine(i);
    }
  

Result: 1.2 Expected: 1,2,0

    
asked by anonymous 04.01.2016 / 01:38

1 answer

3

You can do this:

var pr = new List<int>() { 1, 2, 3 };
var un = new List<int>() { 1, 2 };
var pu = from p in pr
            join u in un on p equals u into u1
            from u2 in u1.DefaultIfEmpty(new int())
            select u2;
foreach (var i in pu)
{
    Console.WriteLine(i);
}
    
04.01.2016 / 15:23