假设我有一个Dictionary对象:
Dictionary myDictionary<int, SomeObject> = new Dictionary<string, SomeObject>();
现在,我想以相反的顺序遍历字典。我不能使用简单的for循环,因为我不知道字典的关键字。foreach很简单:
foreach (SomeObject object in myDictionary.Values)
{
// Do stuff to object
}
但我如何才能反向执行此操作呢?
发布于 2008-09-17 13:24:10
实际上,在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];
}
}
但是当然你不能用字典来做到这一点,因为它没有实现IList或者提供索引器。说字典没有顺序是不正确的:它当然有顺序。如果你知道它是什么,这个命令甚至会很有用。
对于您的问题的解决方案:我建议将元素复制到一个数组中,并使用上面的方法反向遍历它。如下所示:
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);
}
}
将值复制到数组中似乎不是一个好主意,但根据值的类型不同,这并不是很糟糕。你可能只是在复制引用!
https://stackoverflow.com/questions/82881
复制相似问题