Skip to main content
 首页 » 编程设计

c#之为使用查询字符串的 linq 中的 where 语句提供默认值

2024年02月06日24lexus

让我们先看看我的代码

protected void dsVsl_Selecting(object sender, LinqDataSourceSelectEventArgs e) 
{ 
    string query; 
    if (Request.QueryString["[VARIABLE]"] != "" && Request.QueryString["[VARIABLE]"] != null) 
    { 
        query = ""; 
    } 
    else 
    { 
        query = Request.QueryString["vslCat"]; 
    }  
    e.Result = (from b in context.tblVessels 
                where b.vApproval == true 
                where b.vCat == query 
                select new 
                { 
                    b.vAdType, 
                    b.vCat, 
                    b.vID, 
                    b.vAdTitle, 
                    b.vAdDesc, 
                    b.vBuilder, 
                    b.vBuildYear, 
                }).ToList(); 
} 

当第一次加载页面时,没有查询字符串出现,所以我想显示没有任何过滤器的结果,但它什么也没显示!!!。而且我知道我可以将我的 linq 语句放在 if 和 else block 中以具有两个不同的 linq to ADO 语句,但我不想那样做!

请您参考如下方法:

在第一个查询中,您要检查 b.vCat == "" 是否对您要收集的所有行来说都是错误的。而是像这样在您的 where 语句中进行额外检查:

e.Result = (from b in context.tblVessels 
            where b.vApproval == true 
            where (query == "" || b.vCat == query) 
            select new 
            { 
                b.vAdType, 
                b.vCat, 
                b.vID, 
                b.vAdTitle, 
                b.vAdDesc, 
                b.vBuilder, 
                b.vBuildYear, 
            }).ToList();