Possible to iterate backwards through a foreach?

前端 未结 11 2173
无人及你
无人及你 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:27

    As 280Z28 says, for an IList you can just use the index. You could hide this in an extension method:

    public static IEnumerable FastReverse(this IList items)
    {
        for (int i = items.Count-1; i >= 0; i--)
        {
            yield return items[i];
        }
    }
    

    This will be faster than Enumerable.Reverse() which buffers all the data first. (I don't believe Reverse has any optimisations applied in the way that Count() does.) Note that this buffering means that the data is read completely when you first start iterating, whereas FastReverse will "see" any changes made to the list while you iterate. (It will also break if you remove multiple items between iterations.)

    For general sequences, there's no way of iterating in reverse - the sequence could be infinite, for example:

    public static IEnumerable GetStringsOfIncreasingSize()
    {
        string ret = "";
        while (true)
        {
            yield return ret;
            ret = ret + "x";
        }
    }
    

    What would you expect to happen if you tried to iterate over that in reverse?

提交回复
热议问题