如何通过键而不是索引引用列表<对象中的项目>
本文关键字:对象 项目 列表 引用 何通过 索引 | 更新日期: 2023-09-27 18:35:12
我有一个包含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进行引用。
基本上,听起来你想要一个Dictionary<string, City>
而不是一个List<City>
。您可以使用 LINQ 轻松创建以下内容:
var dictionary = list.ToDictionary(city => city.Name);
如果你真的想保留顺序,你可以使用列表并搜索它(根据 Ethan 的答案),但如果你只需要按名称查找,那么字典就是你想要的。
编写一个包装器列表类 CityList 并重载 [] 运算符。
public class City
{
private string name;
private string country;
public City(string cityName)
{
Name = cityName;
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
public class CityList : CollectionBase
{
public CityList() : base ()
{
}
public City this[int index]
{
get
{
return (City)List[index];
}
set
{
List[index] = value;
}
}
public City this[string name]
{
get
{
int index = this.IndexOf(name);
if (index < 0 || index >= this.List.Count) return null; // or assert
return (City)List[index];
}
set
{
int index = this.IndexOf(name);
if (index > 0 || index >= this.List.Count) return; // or assert
List[index] = value;
}
}
public virtual int IndexOf(City city)
{
return List.IndexOf(city);
}
public virtual int IndexOf(string name)
{
if (name == null) return -1;
for (int i = 0; i < List.Count; i++)
{
if (((City)List[i]).Name.ToLower() == name.ToLower())
return i;
}
return -1;
}
public virtual void Insert(int index, City city)
{
List.Insert(index, city);
}
public virtual int Add(City city)
{
return base.List.Add(city);
}
}
class Program
{
static void Main()
{
City NewYork = new City("New York");
City Boston = new City("Boston");
City Tampa = new City("Tampa");
CityList cities = new CityList();
cities.Add(NewYork);
cities.Add(Boston);
cities.Add(Tampa);
Console.WriteLine(cities["Boston"].Name); // prints "Boston"
Console.ReadKey();
}
}
现在可能有一种更光滑的方法可以做到这一点,所以你不需要铸造。这类似于 .NET 2.0 代码。
您可以使用 LINQ:
List<City> theList = new List<City>();
City theCity = theList.FirstOrDefault( x => x.Name == "London" );
System.Collections.ObjectModel.KeyedCollection
怎么样?
http://msdn.microsoft.com/en-us/library/ms132438.aspx