LINQ查询插入存在查询字符串到LINQ查询

时间:2019-01-13 03:38:18

标签: c# linq

我想使查询跟随网站的查询字符串,但是不能以这种方式完成,是否有其他选择可以执行此操作?例如,我可以在查询字符串中插入名称,类型,类,但并非每个变量都需要搜索学生

      if (Request.QueryString["Name"] != null)
        {
            name = Request.QueryString["Name"];
            query += "WHERE c.Name == " + name + " ";
        }

        if (Request.QueryString["Type"] != null)
        {
            type += Request.QueryString["Type"];
            query += "WHERE c.type == "+ type + " ";
        }


        string querytest = query
        var q = "from c in db.Students" + query + "select c";
        GridView1.DataSource = q;
        GridView1.DataBind();

谢谢你!

1 个答案:

答案 0 :(得分:0)

尝试一下:

        var query = from c in db.Students select c;
        if (Request.QueryString["Name"] != null)
        {
            name = Request.QueryString["Name"];
            query = query.Where(c => c.name == name);
        }

        if (Request.QueryString["Type"] != null)
        {
            type += Request.QueryString["Type"];
            query = query.Where(c => c.type == type);
        }

        GridView1.DataSource = query.ToList()