Pan*_*cus 16 .net c# iteration collections
假设我有一个Dictionary对象:
Dictionary myDictionary<int, SomeObject> = new Dictionary<string, SomeObject>();
Run Code Online (Sandbox Code Playgroud)
现在我想以相反的顺序遍历字典.我不能使用简单的for循环,因为我不知道字典的键.一的foreach很简单:
foreach (SomeObject object in myDictionary.Values)
{
// Do stuff to object
}
Run Code Online (Sandbox Code Playgroud)
但是我怎么能反向执行呢?
Jon*_*han 19
我使用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);
Run Code Online (Sandbox Code Playgroud)
值得注意的是,排序列表仅存储按键排序的键/值对.
Chr*_*ham 18
如果你有.NET 3.5,你可以在IEnumerables上使用.Reverse()扩展方法.例如:
foeach (SomeObject o in myDictionary.Values.Reverse())
{
// Do stuff to object
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19183 次 |
| 最近记录: |