Use Defaultifempty in a LINQ query with Join

Asked

Viewed 77 times

3

The goal is to join these two list, being that if in the list pr have an item that does not match the list un, the default value will be returned. I know there are other ways, but I would like 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

1 answer

3


You can do it like 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.