binary binary - 2 months ago 10
ASP.NET (C#) Question

Retrieving all records with Lambda StartsWith()

I have the following ActionResult and retrieve records that starting with "query" parameter's value. However, when quesry value is empty or null, the methods returns no record while I want to retrieve all of them. So, do I have to use a if clause and create different lambda clauses, or is it possible to check query parameter and retrieve all of the records by using StartsWith?

public ActionResult StudentLookup(string query)
{
var students = repository.Students.Select(m => new StudentViewModel
{
Id = m.Id,
Name = m.Name
})
.Where(m => m.Name.StartsWith(query));
return Json(students, JsonRequestBehavior.AllowGet);
}

Answer

Well, two options:

  • Conditionally apply the Where clause:

    IQuerable<StudentModel> students = repository.Students.Select(m => new StudentViewModel
    {
        Id = m.Id,
        Name = m.Name
    });
    if (!string.IsNullOrEmpty(query))
    {
         students= students.Where(m => m.Name.StartsWith(query));
    }
    return Json(students, JsonRequestBehavior.AllowGet);
    
  • Put the check in the Where clause itself:

    var students = repository.Students.Select(m => new StudentViewModel
    {
        Id = m.Id,
        Name = m.Name
    })
    .Where(m => string.IsNullOrEmpty(query) || m.Name.StartsWith(query));
    return Json(students, JsonRequestBehavior.AllowGet);