是否可以使用foreach
语句以相反的顺序遍历Collections对象?
如果不是foreach
声明,还有其他方法吗?
答案 0 :(得分:20)
您可以向后使用正常for
循环,如下所示:
for (int i = collection.Count - 1; i >= 0 ; i--) {
var current = collection[i];
//Do things
}
您也可以使用LINQ:
foreach(var current in collection.Reverse()) {
//Do things
}
然而,正常for
循环可能会更快一些。
答案 1 :(得分:7)
你可以在集合上调用Reverse()。
foreach(var item in collection.Reverse()) { ... }
答案 2 :(得分:4)
如果你使用3.5,看起来在LINQ中有一个Reverse()方法 这不会以相反的顺序迭代,但会反转整个列表,然后你可以做你的foreach。
或者您可以使用简单的for语句:
for(int i = list.Count -1; i >= 0; --i)
{
x = list[i];
}
答案 3 :(得分:4)
或者,如果集合是IEnumerable,因此没有随机访问,请使用System.Linq的IEnumerable.Reverse()方法并照常应用forearch。
using System.Linq;
foreach (var c in collection.Reverse()) {
}
答案 4 :(得分:2)
List<string> items = new List<string>
{
"item 1",
"item 2",
"item 3",
"item 4",
};
lines.AsEnumerable().Reverse()
.Do(a => Console.WriteLine(a), ex => Console.WriteLine(ex.Message), () => Console.WriteLine("Completed"))
.Run();