linq 基于对象内容创建 predicate /表达式

e5nszbig  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(141)
public class Person
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int? Age { get; set; }
}

var persons = new List<Person>
{
    new Person { Id = 1, FirstName = "Fox", LastName = "Mulder", Age = 40 },
    new Person { Id = 2, FirstName = "Dana", LastName = "Scully", Age = 35 }
};

List<Person> Search(List<Person> persons, Person person)
{

    //Here I'd like create a predicate here it's a AND between each.

    //If !string.IsNullOrEmpty(person.FirstName) add to predicate, same for LastName

    //If  person.Age.HasValue() add to predicate

    return persons.Where(myPredicateHere);
}

正如在Search方法中所解释的,我想与AND合并,如果FirstName不为null或空,它是 predicate 的一部分,对于LastName也是如此,如果Age有一个值,则将其添加到 predicate 中。
你知道吗?
谢谢你,

9fkzdhlc

9fkzdhlc1#

除了构建动态 predicate 之外,另一个选择是链接Where调用

List<Person> Search(List<Person> persons, Person person)
{

    IEnumerable<Person> result = persons;
    if(!String.IsNullOrEmpty(person.FirstName))
    {
        result = result.Where(x => x.FirstName == person.FirstName);
    }
    if(!String.IsNullOrEmpty(person.LastName))
    {
        result = result.Where(x => x.LastName == person.LastName);
    }
    if(person.Age.HasValue)
    {
        result = result.Where(x => x.Age == person.Age);
    }
    return result.ToList();
}

示例:https://dotnetfiddle.net/Xs4x8V

v6ylcynt

v6ylcynt2#

像这样的事?

List<Person> Search(List<Person> persons, Person person)
        {
            Func<Person, bool> predicate = x => x.Id == person.Id;

            if (!string.IsNullOrEmpty(person.FirstName))
            {
                predicate = x => !string.IsNullOrEmpty(person.FirstName) && x.Id == person.Id;
            }

            if (!string.IsNullOrEmpty(person.LastName))
            {
                predicate = x => !string.IsNullOrEmpty(person.LastName) && x.Id == person.Id;
            }

            if (person.Age.HasValue)
            {
                predicate = x => person.Age.HasValue && x.Id == person.Id;
            }

            return persons.Where(predicate).ToList();
        }

相关问题