在 C# .NET 2.0 中,反向执行 foreach 的简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/82881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In C# .NET 2.0, what's an easy way to do a foreach in reverse?
提问by Pandincus
Lets say I have a Dictionary object:
假设我有一个 Dictionary 对象:
Dictionary myDictionary<int, SomeObject> = new Dictionary<string, SomeObject>();
Now I want to iterate through the dictionary in reverse order. I can't use a simple for loop because I don't know the keys of the dictionary. A foreachis easy:
现在我想以相反的顺序遍历字典。我不能使用简单的 for 循环,因为我不知道字典的键。一的foreach很简单:
foreach (SomeObject object in myDictionary.Values)
{
// Do stuff to object
}
But how can I perform this in reverse?
但是我如何才能反向执行此操作?
采纳答案by Jonathan
I'd use a SortedList instead of a dictionary. You can still access it by Key, but you can access it by index as well.
我会使用 SortedList 而不是字典。您仍然可以通过 Key 访问它,但您也可以通过索引访问它。
SortedList sCol = new SortedList();
sCol.Add("bee", "Some extended string matching bee");
sCol.Add("ay", "value matching ay");
sCol.Add("cee", "Just a standard cee");
// Go through it backwards.
for (int i = sCol.Count - 1; i >=0 ; i--)
Console.WriteLine("sCol[" + i.ToString() + "] = " + sCol.GetByIndex(i));
// Reference By Key
foreach (string i in sCol.Keys)
Console.WriteLine("sCol[" + i + "] = " + sCol[i]);
// Enumerate all values
foreach (string i in sCol.Values)
Console.WriteLine(i);
It's worth noting that a sorted list stores key/value pairs sorted by key only.
值得注意的是,排序列表仅存储按键排序的键/值对。
回答by leppie
A dictionary or any other form of hashtable has no ordering. So what you are trying to do is pointless :)
字典或任何其他形式的哈希表没有排序。所以你试图做的是毫无意义的:)
回答by leppie
That would be a Dictionary<int, SomeObject> myDictionary
, and you would do it by:
那将是一个Dictionary<int, SomeObject> myDictionary
,你可以通过以下方式做到这一点:
foreach(SomeObject _object in myDictionary.Values.Reverse())
{
}
回答by Timothy Carter
If the ordering is most important, you could you a Stack and create a simple struct to store your int, Object pair.
如果排序最重要,您可以使用 Stack 并创建一个简单的结构来存储您的 int、Object 对。
回答by Chris Wenham
If you have .NET 3.5 you can use the .Reverse() extension method on IEnumerables. For example:
如果您有 .NET 3.5,您可以在 IEnumerables 上使用 .Reverse() 扩展方法。例如:
foeach (SomeObject o in myDictionary.Values.Reverse())
{
// Do stuff to object
}
回答by Stormenet
The only way I can come up with in .NET 2.0is to first copy all the values to a List, reverse the list and then run the foreach on that list:
我能在.NET 2.0 中想出的唯一方法是首先将所有值复制到一个列表,反转列表,然后在该列表上运行 foreach:
Dictionary<int, object> d;
List<object> tmplist;
foreach (object o in d.Values) tmplist.Add(s);
tmplist.Reverse();
foreach (object o in tmplist) {
//Do stuff
}
回答by OwenP
I agree with @leppie, but think you deserve an answer to the question in general. It could be that you meant for the question to be in general, but accidentally picked a bad data structure. The order of the values in a dictionary should be considered implementation-specific; according to the documentation it is always the same order as the keys, but this order is unspecified as well.
我同意@leppie,但我认为你应该得到这个问题的总体答案。可能是您的意思是一般问题,但不小心选择了错误的数据结构。字典中值的顺序应该被认为是特定于实现的;根据文档,它始终与键的顺序相同,但此顺序也未指定。
Anyway, there's not a straightforward way to make foreach
work in reverse. It's syntactic sugar to using the class's enumerator, and enumerators can only travel in one direction. Technically the answer could be "reverse the collection, then enumerate", but I think this is a case where you'll just have to use a "backwards" for loop:
无论如何,没有一种直接的方法可以foreach
反向工作。使用类的枚举器是语法糖,枚举器只能在一个方向上移动。从技术上讲,答案可能是“反转集合,然后枚举”,但我认为在这种情况下,您只需要使用“向后”for 循环:
for (int i = myCollection.Length - 1; i >= 0; i--)
{
// do something
}
回答by Gord
If you want a dictionary type collection but you need to maintain the insertion order you can look into the KeyedCollection here
如果你想要一个字典类型的集合但你需要维护插入顺序,你可以在这里查看 KeyedCollection
It is a merger between a dictionary and a list. That way you can access elements in the collection via the key or the insertion index.
它是字典和列表的合并。这样你就可以通过键或插入索引访问集合中的元素。
The only gotcha is if your element being stored in the collection has to have an int key. If you could change that to a string or another type (Guid Mabye). Since collection1will be searching for the key of 1 rather than the index of 1.
唯一的问题是如果您的元素存储在集合中必须有一个 int 键。如果您可以将其更改为字符串或其他类型(Guid Mabye)。因为集合1将搜索1的键而不是 1 的索引。
回答by Aaron Powell
A standard for
loop would be best. You don't have to worry about the processing overhead of reversing the collection.
for
最好是标准循环。您不必担心反转集合的处理开销。
回答by Dave Van den Eynde
Actually, in C# 2.0 you can create your own iterator that traverses a container in reverse. Then, you can use that iterator in your foreach statement. But your iterator would have to have a way of navigating the container in the first place. If it's a simple array, it could go backwards like this:
实际上,在 C# 2.0 中,您可以创建自己的迭代器来反向遍历容器。然后,您可以在 foreach 语句中使用该迭代器。但是您的迭代器首先必须有一种导航容器的方法。如果它是一个简单的数组,它可以像这样倒退:
static IEnumerable<T> CreateReverseIterator<T>(IList<T> list)
{
int count = list.Count;
for (int i = count - 1; i >= 0; --i)
{
yield return list[i];
}
}
But of course you can't do that with a Dictionary as it doesn't implement IList or provides an indexer. Saying that a Dictionary does not have order is not true: of course it has order. That order can even be useful if you know what it is.
但是当然您不能使用 Dictionary 来做到这一点,因为它没有实现 IList 或提供索引器。说字典没有顺序是不正确的:它当然有顺序。如果您知道它是什么,该顺序甚至可能很有用。
For a solution to your problem: I'd say copy the elements to an array, and use the above method to traverse it in reverse. Like this:
为了解决您的问题:我会说将元素复制到一个数组,然后使用上述方法反向遍历它。像这样:
static void Main(string[] args)
{
Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "value1";
dict[2] = "value2";
dict[3] = "value3";
foreach (KeyValuePair<int, string> item in dict)
{
Console.WriteLine("Key : {0}, Value: {1}", new object[] { item.Key, item.Value });
}
string[] values = new string[dict.Values.Count];
dict.Values.CopyTo(values, 0);
foreach (string value in CreateReverseIterator(values))
{
Console.WriteLine("Value: {0}", value);
}
}
Copying your values to an array may seem like a bad idea, but depending on the type of value it's not really that bad. You might just be copying references!
将您的值复制到数组似乎是一个坏主意,但根据值的类型,它并不是那么糟糕。您可能只是在复制参考资料!