English 中文(简体)
我如何用“ 键” 而不是索引来指列表中“ 对象” 的项目?
原标题:How do I refer to an item in a list<object> by Key rather than index?
  • 时间:2012-05-23 19:21:03
  •  标签:
  • c#
  • list
  • key

我有一个包含 List< & gt; 对象类。 对于这个示例, 我会说对象是以下基本类 :

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来表示。

最佳回答

您写了一张包装列表类城市列表, 并超载了 [ ] 操作员 。

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 代码 。

问题回答

基本上,它听起来像您想要一个 dictionary<string; City> 而不是一个 List< City> 。 您可以很容易地用 LINQ 创建它 :

var dictionary = list.ToDictionary(city => city.Name);

如果您真的想要保存命令, 您可以使用列表并通过它搜索( 根据 Ethan 的回答), 但是如果您只需要 < em> 来查找名称, 那么字典就是您想要的 。

您可以使用 LINQ:

List<City> theList = new List<City>();
City theCity = theList.FirstOrDefault( x => x.Name == "London" );




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签