I apologize in advance for my English.

I have a user search method. It's parameters - login and strict. The last one determines, which method should have been used for search - Equals (strict is true) or Contains (strict is false). How should I implement it? I could do two different methods, but I think it would be code repeating.

    public async Task<List<UserFindInfoDTO>> FindUserByLoginAsync(string login, bool strict)
        var users = await context.Users
            .Where(u => u.Nickname.Equals(login)) // change on "Contains" if strict is false
            .Select(u => new UserFindInfoDTO
                Status  = u.Status,
                Id = u.Id,
                MiniAvatar =  u.Image,
                Nickname = u.Nickname                    
        return users;
  • 4
    \$\begingroup\$ If the code is unfinished, it's not ready for review. Please take a look at the help center. \$\endgroup\$ – Mast Jul 3 '20 at 6:06

The lambda expression you pass to Where() is where you define the condition, so this is where it makes the most sense to put all the logic for this.

.Where(u => strict ? u.Nickname.Equals(login) : u.Nickname.Contains(login))

Or for higher performance you can conditionally pass a different lambda expression:

Func<User,bool> checker = strict
  ? (Func<User,bool>)((User u) => u.Nickname.Equals(login))
  : (Func<User,bool>)((User u) => u.Nickname.Contains(login));


  • \$\begingroup\$ I thought about it but I am afraid that the program will check this condition for every string. Or it will check once and choose the necessary method for all strings? \$\endgroup\$ – ZOOM SMASH Jul 2 '20 at 21:41
  • \$\begingroup\$ @ZOOMSMASH You can conditionally choose between lambda expressions, I added an example of it to my answer. \$\endgroup\$ – potato Jul 2 '20 at 21:55
  • \$\begingroup\$ Yeah I added one too many, removed it now. And you're welcome :) \$\endgroup\$ – potato Jul 2 '20 at 22:03
  • \$\begingroup\$ @ZOOMSMASH Also I just realized I assigned the type bool to the lambda input instead of the user object! \$\endgroup\$ – potato Jul 2 '20 at 22:07
  • \$\begingroup\$ Yeah, and I don't want to be meticulous, but check brackets again :D \$\endgroup\$ – ZOOM SMASH Jul 2 '20 at 22:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.