我创建了一个 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);
}
}
}
List
但具有像Insert、Remove、IndexOf这样的方法 - 但不仅仅是通过整数索引器添加项目和检索,还可以通过其他方式访问它们 - 通常是字符串。DataTable中的DataRow类就是这样运作的。 - mattmc3