user3488442
user3488442

Reputation: 99

Add code in runtime

Let's say I have a list of strings. Based on the value of the strings I want to add code.

E.g., I have three strings; first name, last name, and e-mail address. They could be null or empty. Lets say last name and e-mail are empty, then I would like the following code:

repository.Find(dto => dto.FirstName == firstName)
          .Select(x => CreateAccount(x)).ToList();

When only email is empty, then the code should look like this:

accountRepository.Find(dto => dto.FirstName == firstName ||
                       dto.LastName == lastName)
                 .Select(x => CreateAccount(x)).ToList();

In other words, when looping through the strings, I want to add code when the strings are not empty. Is this at all possible?

Upvotes: 1

Views: 67

Answers (1)

Karel
Karel

Reputation: 36

You could modify the Find predicate:

accountRepository.Find(dto => 
    (string.IsNullOrEmpty(firstName) ? false : dto.FirstName == firstName) || 
    (string.IsNullOrEmpty(lastName) ? false : dto.LastName == lastName) ||
    (string.IsNullOrEmpty(email) ? false : dto.Email == email))
    .Select(x => CreateAccount(x)).ToList();

Upvotes: 2

Related Questions