ASP.NET C#LINQ条件WHERE子句 [英] ASP.NET C# LINQ conditional WHERE clause

查看:581
本文介绍了ASP.NET C#LINQ条件WHERE子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从众多下拉列表中获取值,并根据所选择的选项构建一个where语句.如果不选择它们,则应将它们从select语句中排除.

I'm trying to get values from numerous dropdown lists and build a where statement depending on the options selected. If they are not slected then they should be excluded from the select statement.

这就是我本来应该做的,但我认为使用linq无法以这种方式完成它.

This is how I would have done it but I gather that it can not be done in this way with linq.

 IEnumerable<IGrouping<string, Forest>> treeQuery =

        from trees in Forest
        if (ddlType1.SelectedValue!=null)
        {
            string strWhere += trees.Type1 == ddlType1.SelectedValue
        }
        else if (ddlType2.SelectedValue!=null)
        {
            string strWhere += trees.Type2 == ddlType2.SelectedValue
        }
        where strWhere
        orderby trees.Nuts
        group trees by trees.TrunkColour;

任何帮助将不胜感激.

这是我在...中添加示例之前的代码.

This is the code before I added the example in...

 IEnumerable<IGrouping<string, Forest>> treeQuery =

        from trees in Forest
        where trees.Type1 == "oak"
        orderby trees.Nuts
        group trees by trees.TrunkColour; 

推荐答案

对于每个下拉菜单,您都可以在其中添加一个子句:

For each one of your dropdowns, you can add a clause to your where:

where (ddlType1.SelectedValue == "" || trees.Type1 == ddlType1.SelectedValue)
    && (ddlType2.SelectedValue == "" || trees.Type2 == ddlType2.SelectedValue)
    // && ( type 3... )

这篇关于ASP.NET C#LINQ条件WHERE子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆