Reputation: 269
I am passing assesment model to the Results Action using redirect to action. In the Results action controller I would like to to execute a linq statement to retrieve the number of rows using the repository and whatever values are posted.for example
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();
}
}
Upvotes: 0
Views: 4118
Reputation: 14846
There's an overload of the Count method that takes a predicate. With it the query can be simplified to something like:
int totalSmokers = xs.Count(x =>
x.SmokesInHouse == a.SmokesInHouse &&
x.SmokesInCar == a.SmokesInCar &&
x.SmokesAtWork == a.SmokesAtWork);
I'm assuming this is an IQueryable that will be executed on the server and it might not make difference. But if it was an IEnumerable it could make a difference for large sequences.
Upvotes: 0
Reputation: 36
Try the following to get the total number of smokers in your model:
int totalSmokers = model.Where(x => x.SmokesInHouse && x.SmokesInCar && x.SmokesAtWork).Count();
You would use the same where clause if querying from a database table.
Upvotes: 1
Reputation: 82096
You need to update the Results
action to accept the Assessment
model i.e.
[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);
}
Upvotes: 3