简体   繁体   中英

How can I shorten an if without else statement with lambda?

the following is the code and I do not know how to achieve the following using lambda

public void AddClimber(string name, int age, Skill skill)  
{
   if (GetClimber(name) == null)
   {
        Climber toAdd = new Climber(name, age, skill);
        this.climbers.Add(toAdd);

        if (AddedLowLevelClimer != null)
        {
            if (skill == Skill.LOW) { AddedLowLevelClimer(toAdd); }
        }
        else if (AddedMediumLevelClimer != null)
        {
            if (skill == Skill.LOW) { AddedMediumLevelClimer(toAdd); }
        }
        else if (AddedHighLevelClimer != null)
        {
            if (skill == Skill.LOW) { AddedHighLevelClimer(toAdd); }
        }
        else if (AddedProLevelClimer != null)
        {
            if (skill == Skill.LOW) { AddedProLevelClimer(toAdd); }
        }           
    }
}

You may try to use a null coalescing operator to choose the first non-null handler:

    var target = AddedLowLevelClimer
                         ?? AddedMediumLevelClimer 
                         ?? AddedHighLevelClimer 
                         ?? AddedProLevelClimer;
    if (target != null)
    {
        if (skill == Skill.LOW) 
            target(toAdd); 
    }           

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM