列名称的Linq占位符

本文关键字:Linq 占位符 | 更新日期: 2023-09-27 17:54:02

我必须将radioButtons的值动态地放入Linq查询中,以便该值用radioButton的值替换下面代码中的customerName。这一切都存在于带有实体框架的MVC项目中。那么我如何在Linq查询中编写占位符呢?

public ActionResult Index(string whatToSearchFor, string radioButtonValue)
{
    if (search == null)
    {
        var results = from p in db.Orders
                      select p;
        ViewBag.Orders = results;
        return View();
    }
    else
    {
        var results = from p in db.Orders
                      where values
                      where p.customerName.StartsWith(search)
                      select p;
        ViewBag.Orders = results;
        return View();
    }
}

更新和为我工作的:

public ActionResult Index(string whatToSearchFor, string radioButtonValue)
{
    if(radioButtonValue == "NameOfTheRadioButton1")
    {
        var results = from p in db.Orders
                      where values
                      where p.column1.StartsWith(search)
                      select p;
        ViewBag.Orders = results;
        return View();
    }
    else if(radioButtonValue == "NameOfTheRadioButton2")
    {
        var results = from p in db.Orders
                      where values
                      where p.column2.StartsWith(search)
                      select p;
        ViewBag.Orders = results;
        return View();
    }
    else
    {
        var results = from p in db.Orders
                      select p;
        ViewBag.Orders = results;
        return View();
    }
}

列名称的Linq占位符

您将不得不从使用查询语法切换到使用lambda语法。

Expression<Func<Order, bool>> condition = null;
if( rbFirst.Checked )
    condition = o => o.FirstThing.StartsWith( search );
else if( rbSecond.Checked )
    condition = o => o.SecondThing.StartsWith( search );
// etc...
var results = db.Orders.Where( condition );