Linq语句返回行数

本文关键字:返回 语句 Linq | 更新日期: 2023-09-27 18:12:30

我使用重定向到操作将评估模型传递给Results Action。在结果动作控制器中,我想执行linq语句来检索使用存储库的行数和所提交的值。例如

number of rows = Select * 
                 from table or model
                 where SmokesInHouse = SmokesInHouse And
                       SmokesInCar = SmokesInCar And
                       SmokesAtWork = SmokesAtWork'
public class SampleController : Controller
{
    private IEnvRepository repository;
    public SampleController(IEnvRepository assesmentRepository)
    {
        repository = assesmentRepository;
    }
    [HttpPost]
    public ActionResult SmokingEnvironments(Assessment a)
    {
        if (ModelState.IsValid)
            return RedirectToAction("Results", new { SmokesInHouse =SmokesInHouse,        SmokesInCar  = a.SmokesInCar, SmokesAtWork=a.SmokesAtWork });
        }
        return View(a);
    }
    [HttpGet]
    public ActionResult Results()
    {
        return View();
    }
}

Linq语句返回行数

您需要更新Results动作以接受Assessment模型,即

[HttpGet]
public ActionResult Results(AssessmentModel assessment)
{
    int rows = myTable.Where(x => x.SmokesInHouse == assessment.SmokesInHouse &&
                                  x.SmokesInCar == assessment.SmokesInCar &&
                                  x.SmokesAtWork == assessment.SmokesInWork).Count();
    return View(rows);
}

尝试以下操作以获取模型中吸烟者的总数:

int totalSmokers = model.Where(x => x.SmokesInHouse && x.SmokesInCar && x.SmokesAtWork).Count();

如果从数据库表中查询,可以使用相同的where子句。

Count方法有一个重载,它接受一个谓词。有了它,查询可以简化为如下内容:

int totalSmokers = xs.Count(x =>
    x.SmokesInHouse == a.SmokesInHouse &&
    x.SmokesInCar == a.SmokesInCar &&
    x.SmokesAtWork == a.SmokesAtWork);

我假设这是一个将在服务器上执行的IQueryable,它可能没有什么区别。但是如果它是IEnumerable,那么对于大的序列就会有所不同。