Possible to iterate backwards through a foreach?

前端 未结 11 2183
无人及你
无人及你 2020-11-27 03:54

I know I could use a for statement and achieve the same effect, but can I loop backwards through a foreach loop in C#?

11条回答
  •  情歌与酒
    2020-11-27 04:46

    Elaborateling slighty on the nice answer by Jon Skeet, this could be versatile:

    public static IEnumerable Directional(this IList items, bool Forwards) {
        if (Forwards) foreach (T item in items) yield return item;
        else for (int i = items.Count-1; 0<=i; i--) yield return items[i];
    }
    

    And then use as

    foreach (var item in myList.Directional(forwardsCondition)) {
        .
        .
    }
    

提交回复
热议问题