Home > OS >  Create a predicate / expression based on object content
Create a predicate / expression based on object content

Time:11-08

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

As explained in the Search method I'd like combine with a AND, if FirstName is not null or empty it's part of the predicate, same for LastName and if the Age has a value add it to the predicate.

Any idea ?

Thanks,

CodePudding user response:

Another option apart from build up a dynamic predicate, is to chain Where calls

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

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

CodePudding user response:

Something like that?

List<Person> Search(List<Person> persons, Person person)
        {
            Func<Person, bool>? predicate = null;

            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();
        }
  • Related