Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Linq Left Join

Tags:

c#

.net

linq

I have seen a number of examples on this but re-producting them in this example does not seem to work. Does anyone have any ideas what is wrong with the following code....

    var products = new[]
    { 
        new {ProductName ="Soda", Category = "Beverages"},
        new {ProductName ="Tuna", Category = "SeaFood"},
        new {ProductName ="Jam", Category = "Condiment"}
    };

    var categories = new[]
    { 
        new {Category = "Beverages", Description="Slurp"},
        new {Category = "SeaFood" , Description="Nosh"},
        new {Category = "Exotic" , Description="Spicy!"},
    };

    var q = from c in categories
                 join p in products on c.Category equals p.Category into tmp
                 from prd in tmp.DefaultIfEmpty()
                 select new { Category = c.Category, 
                              Description = c.Description,        
                              ProductName = prd.ProductName };

Many Thanks in advance

Keith

like image 992
user358311 Avatar asked Dec 04 '25 15:12

user358311


1 Answers

The problem is that there is no product in the category "Exotic", so there is a NullReferenceException thrown when trying to read the product name (in the last code line).

For the code not to crash you can add a null check:

var q = from c in categories
        join p in products on c.Category equals p.Category into tmp
        from prd in tmp.DefaultIfEmpty()
        select new
        {
            Category = c.Category,
            Description = c.Description,
            ProductName = prd != null ?  prd.ProductName : "[null]"
        };
like image 198
Fredrik Mörk Avatar answered Dec 07 '25 05:12

Fredrik Mörk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!