Edw*_*uay 10 c# indexing dictionary
我创建了一个Dictionary<string, string>
集合,以便我可以通过字符串标识符快速引用这些项目.
但我现在还需要通过索引计数器访问这个集合(foreach在我的实例中不起作用).
我需要对下面的集合做什么,以便我也可以通过整数索引访问它的项目?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestDict92929
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> events = new Dictionary<string, string>();
events.Add("first", "this is the first one");
events.Add("second", "this is the second one");
events.Add("third", "this is the third one");
string description = events["second"];
Console.WriteLine(description);
string description = events[1]; //error
Console.WriteLine(description);
}
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*ott 15
你不能.而你的问题推断你的信念Dictionary<TKey, TValue>
是一个有序的清单.它不是.如果您需要有序字典,则此类型不适合您.
也许OrderedDictionary是你的朋友.它提供整数索引.
小智 5
你不能.如上所述 - 字典没有订单.
使您的OWN CONTAINER公开IList
和IDictionary
...并在内部管理(列表和字典).这就是我在这些情况下所做的.所以,我可以使用这两种方法.
基本上
class MyOwnContainer : IList, IDictionary
Run Code Online (Sandbox Code Playgroud)
然后在内部
IList _list = xxx
IDictionary _dictionary = xxx
Run Code Online (Sandbox Code Playgroud)
然后在添加/删除/更改...更新两者.
归档时间: |
|
查看次数: |
1849 次 |
最近记录: |