【发布时间】:2012-05-23 19:21:03
【问题描述】:
我有一个包含List<> 对象的类。对于这个例子,我会说对象是一个基本类,如下所示:
public class City
{
private string name;
private string country;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
通常我会这样引用这些对象:
List<City> theList = new List<City>();
City theCity = theList[0];
我想做的是参考以下列表:
List<City> theList = new List<City>();
City theCity = theList["London"];
其中伦敦是其中一个城市的名称属性。
我如何实现这一目标?目前我一直在构建“查找”类型的方法来返回我所讨论的城市。我需要的是能够通过Key引用。
【问题讨论】:
-
您不能确定列表中只有一个具有指定“键”的项目。最好使用字典。