I have this code, I want to change Where from
Where(p => p.FirstName.StartsWith(v))
to
Where(p => (p.FirstName p.LastName).Contains(v) if v.length > 1
[HttpGet("search")]
public IActionResult SearchPerson([FromQuery] string v="A", [FromQuery] int page=1)
{
var personList = _ctx.People.Where(p => p.FirstName.StartsWith(v))
.Skip((page - 1) * 30)
.Take(30);
return Ok(personList);
}
Is it possible ?
CodePudding user response:
You could add the Where clause, or any number of Where clauses, like this. It is not clear what you want to do if v
length is not greater than 1, but I hope you get the idea:
IEnumerable<Person> personList = ctx.People;
if(v.length > 1)
{
personList = personList.Where(p => (p.FirstName p.LastName).Contains(v));
}
else
{
//a different Where clause?
}
return Ok(personList.Skip((page - 1) * 30).Take(30));
CodePudding user response:
You need something like this:
_ctx.People.Where(p =>
{
if (v.Length > 1)
{
return (p.FirstName p.LastName).Contains(v);
}
return true;
})
but you can also combine them with && just like @Qwerty said :)
CodePudding user response:
You can use && within Where
clause to combine two conditions
Sample :
List<Person> people = new List<Person>();
people.Add(new Person() { FirstName = "1", LastName = "8" });
people.Add(new Person() { FirstName = "1", LastName = "8" });
people.Add(new Person() { FirstName = "1", LastName = "8" });
people.Add(new Person() { FirstName = "1", LastName = "8" });
people.Add(new Person() { FirstName = "1", LastName = "8" });
people.Add(new Person() { FirstName = "2", LastName = "8" });
var test = "1";
var list1 = people.Where(p => test.Length > 0 && (p.FirstName p.LastName).StartsWith(test)).ToList();