我正在尝试使用以下linq到sql查询来获取结果。但是如果parentCategoryId传递为null
,则它不起作用 public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId)
{
var categories = from c in source where c.ParenCategoryId == parentCategoryId select c;
return categories;
}
但如果null直接用于替代parentCategoryId
,则后续工作 public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId)
{
var categories = from c in source where c.ParenCategoryId == null select c;
return categories;
}
答案 0 :(得分:8)
您可以使用object.Equals
,它也会匹配null
值。
public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId)
{
var categories = from c in source
where object.Equals(c.ParenCategoryId, parentCategoryId)
select c;
return categories;
}
答案 1 :(得分:0)
您可以尝试以下
public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId)
{
var categories = from c in source
where (parentCategoryId != null? c.ParenCategoryId == parentCategoryId : c.ParenCategoryId == null)
select c;
return categories;
}