如何通过C#集合反向遍历? [英] How can you reverse traverse through a C# collection?

查看:920
本文介绍了如何通过C#集合反向遍历?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可能有一条 foreach 语句将以相反的顺序遍历Collections对象?

Is it possible to have a foreach statement that will traverse through a Collections object in reverse order?

如果不是 foreach 语句,还有其他方法吗?

If not a foreach statement, is there another way?

推荐答案

您可以使用普通的 for 向后循环,例如:

You can use a normal for loop backwards, like this:

for (int i = collection.Count - 1; i >= 0 ; i--) {
    var current = collection[i];
    //Do things
}

您还可以使用LINQ:

You can also use LINQ:

foreach(var current in collection.Reverse()) {
    //Do things
}

但是,正常的 for 循环可能会有点快一点。

However, the normal for loop will probably be a little bit faster.

这篇关于如何通过C#集合反向遍历?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆