65.9K
CodeProject is changing. Read more.
Home

Call Functions Until One Meets Condition

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Mar 29, 2011

CPOL
viewsIcon

5340

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