我已经看到了很多这样的例子,但是在这个例子中重新生成它们似乎不起作用。有没有人有任何想法以下代码有什么问题....
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 };
非常感谢提前
基思
答案 0 :(得分:1)
问题是“异国情调”类别中没有产品,因此在尝试阅读产品名称时(在最后一个代码行中)会抛出NullReferenceException
。
对于不崩溃的代码,您可以添加空检查:
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]"
};