Linq语句返回行数

时间:2013-05-06 14:36:24

标签: c# asp.net-mvc linq razor

我正在使用重定向到操作将评估模型传递给结果操作。在结果动作控制器中我想 执行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();
    }
}

3 个答案:

答案 0 :(得分:3)

您需要更新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);
}

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:0)

带有谓词的Count method超载。有了它,查询可以简化为:

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

我假设这是一个将在服务器上执行的IQueryable,它可能没有什么区别。但如果它是一个IEnumerable,它可能会对大型序列产生影响。