是否可以有一个foreach
语句以相反的顺序遍历 Collections 对象?
如果不是foreach
声明,还有其他方法吗?
您可以向后使用正常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
循环可能会快一点。
你可以在集合上调用Reverse() 。
foreach(var item in collection.Reverse()) { ... }
如果您使用的是 3.5,看起来 LINQ 中有一个 Reverse() 方法不会以相反的顺序遍历,而是会反转整个列表,那么您可以执行 foreach。
或者你可以使用一个简单的 for 语句:
for(int i = list.Count -1; i >= 0; --i)
{
x = list[i];
}
或者,如果集合是 IEnumerable 并因此没有随机访问,请使用 System.Linq 的 IEnumerable.Reverse() 方法并照常应用 forsearch。
using System.Linq;
foreach (var c in collection.Reverse()) {
}
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();