Problem with Linq Left Join

I saw several examples of this, but re-creating them in this example does not seem to work. Does anyone have any idea 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 };

Thank you very much in advance

Whale

+3
source share
1 answer

The problem is that there is no product in the Exotic category, so when you try to read the product name (in the last line of code) appears NullReferenceException.

To prevent the code from crashing, 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]"
        };
+1
source

Source: https://habr.com/ru/post/1748499/


All Articles