Possible to iterate backwards through a foreach?

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

    If you use a List, you can also use this code:

    List list = new List();
    list.Add("1");
    list.Add("2");
    list.Add("3");
    list.Reverse();
    

    This is a method that write the list reverse in itself.

    Now the foreach:

    foreach(string s in list)
    {
        Console.WriteLine(s);
    }
    

    The output is:

    3
    2
    1
    

提交回复
热议问题