是否可以将LINQ where filter设为条件式?

jhdbpxl9  于 2022-12-06  发布在  其他
关注(0)|答案(3)|浏览(145)

我有此代码,我想更改从何处开始
Where(p => p.FirstName.StartsWith(v))

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);
}

有可能吗?

juud5qan

juud5qan1#

你可以添加Where子句,或者任意数量的Where子句,如下所示。如果v length不大于1,你想做什么还不清楚,但我希望你能明白:

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));
vybvopom

vybvopom2#

你需要这样的东西:

_ctx.People.Where(p =>
{
    if (v.Length > 1)
    {
        return (p.FirstName + p.LastName).Contains(v);
    }

    return true;
})

但你也可以把它们和&&结合起来,就像@Qwerty说的:)

chhkpiq4

chhkpiq43#

您可以在Where子句中使用&&来合并两个条件
样品:

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();

相关问题