Click here to Skip to main content
15,880,891 members
Articles / Programming Languages / Visual Basic
Alternative
Tip/Trick

Call Functions Until One Meets Condition

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
29 Mar 2011CPOL 5.1K   1   1
Sorry, but could not resist :)Being that we we started with select case (in the launge), I felt that this was missing both the initial condition and the action to perform for the case that got hit.So given this:static Action SelectCase(T conditionValue, List<System.Tuple<Func<T,...
Sorry, but could not resist :)

Being that we we started with select case (in the launge), I felt that this was missing both the initial condition and the action to perform for the case that got hit.

So given this:
C#
static Action SelectCase<T>(T conditionValue, List<System.Tuple<Func<T, bool>, 
                                  Action>> conditions)
{
    return (from c in conditions
            where c.Item1(conditionValue)
            select c.Item2).FirstOrDefault();
}

static Action SelectCase<T>(Func<T> conditionValue, 
       List<System.Tuple<Func<T, bool>, Action>> conditions)
{
    return SelectCase<T>(conditionValue(), conditions);
}

I could make a nasty (not as clean as yours) call:
C#
SelectCase<int>(() => DateTime.Now.Second,
    new List<Tuple<Func<int, bool>, Action>>() {
        new Tuple<Func<int, bool>, Action>( (i)=>i==9, Step1),
        new Tuple<Func<int, bool>, Action>( IsBetween10And20, ()=>step2(5, 7)),
        new Tuple<Func<int, bool>, Action>( (i)=>true, ()=>Console.WriteLine("Default action for"))
})();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralFYI, I updated my tip/trick to include an example of using a... Pin
AspDotNetDev29-Mar-11 10:07
protectorAspDotNetDev29-Mar-11 10:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.