我有一个包含一个List<>对象的类.对于这个例子,我会说对象是一个基本类,如下所示:
public class City
{
private string name;
private string country;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
通常我会像这样引用这些对象:
List<City> theList = new List<City>();
City theCity = theList[0];
Run Code Online (Sandbox Code Playgroud)
我想做的是参考如下列表:
List<City> theList = new List<City>();
City theCity = theList["London"];
Run Code Online (Sandbox Code Playgroud)
伦敦是其中一个城市的名称财产.
我该如何实现这一目标?目前我一直在构建"查找"类型的方法,让我回到有问题的城市.我需要的是能够通过Key引用.
基本上,听起来你想要一个Dictionary<string, City>而不是一个List<City>.您可以使用LINQ轻松创建:
var dictionary = list.ToDictionary(city => city.Name);
Run Code Online (Sandbox Code Playgroud)
如果你真的想要保留订单,你可以使用一个列表并搜索它(根据Ethan的答案),但是如果你只需要按名称查找,那么字典就是你想要的.