asp.net mvc 4-对LINQ where子句感到困惑


public ViewResult List(string category, int page = 1) 
{
    ProductsListViewModel viewModel = new ProductsListViewModel
    {
        Products = repository.Products
            .Where(p => category == null || p.Category == category)
            ...........

.Where(p => category == null || p.Category == category)这句话让我有点困惑。逻辑是:"如果类别为空,那么只选择所选的类别"。这是一本书,但这是写这本书的最佳方式吗?它说类别可以是"null或类别值"。所以,如果类别包含一个值,它将使用该值来选择项目,而不是null(null选择所有项目(。我写的这篇文章有点无用,但有效,而且更清晰:

.Where(p => category == null ? category == null :
                               p.Category == category)

我的逻辑正确吗?

它基本上允许类别过滤器是可选的-如果category参数不是null,那么它必须匹配您正在查看的任何内容。否则,只包括所有类别。

.Where(p => category == null || p.Category == category)

这里有两个部分,通过OR连接,这意味着其中一个必须是true,才能产生true:

category == null 

给定的类别为空

p.Category == category

有问题的类别与给定的类别匹配

因此,如果给定的类别为空,或者与p的类别匹配,它将选择一个p

.Where(p => category == null || p.Category == category)

将被转换为SQL查询,类似于以下内容(不完全如此(:

where null is null or Category == null    // When not specified, show all because, null IS null = true
// or
where 'someCategory' is null or Category == 'SomeCategoy'  // filter by some category

三元将返回bool,而不是构造SQL查询的条件

category == null ? category == null : p.Category == category