Neat way to write loop that has special logic for the first item in a collection

后端 未结 12 2577
忘了有多久
忘了有多久 2021-02-13 17:31

Often I have to code a loop that needs a special case for the first item, the code never seems as clear as it should ideally be.

Short of a redesign of the C# language,

12条回答
  •  情歌与酒
    2021-02-13 17:43

    You could try:

    collection.first(x=>
    {
        //...
    }).rest(x=>
    {
        //...
    }).run();
    

    first / rest would look like:

    FirstPart first(this IEnumerable c, Action a)
    {
        return new FirstPart(c, a);
    }
    
    FirstRest rest(this FirstPart fp, Action a)
    {
        return new FirstRest(fp.Collection, fp.Action, a);
    }
    

    You would need to define classed FirstPart and FirstRest. FirstRest would need a run method like so (Collection, FirstAction, and RestAction are properties):

    void run()
    {
        bool first = true;
        foreach (var x in Collection)
        {
            if (first) {
                FirstAction(x);
                first = false;
            }
            else {
                 RestAction(x);
            }
        }
    }
    

提交回复
热议问题