C # Reference object in collection using string instead of integer

I have a set of objects stored in a list.

I would like to refer to an object using a string name instead of an integer.

List<Foo> fooList = new List<Foo>;
Foo item = fooList["Foo Name"]

instead:

List<Foo> fooList = new List<Foo>;
Foo item = fooList[0]

I thought I needed to create a collection class that inherits from List, but from there I'm not sure.

+5
source share
7 answers

Dictionary<string, Foo> is the type you want.

+14
source

Joren's answer is go-to, but if you need to maintain a consistent order for some other logic, And the name you want to associate with the object can be a member of this object, which can do a little Linq trick:

List<Foo> fooList = new List<Foo>;
Foo item = fooList.FirstOrDefault(f=>f.Name == "Foo Name");

"indexer" , :

public class MyList:List<Foo>
{
   public Foo this[string name]
   {
      get { return this.FirstOrDefault(f=>f.Name == "Foo Name"); }
   }
}

..., , ( )

+2

Dictionary<string,Your_Object_type>;

, .

+1

. :

var fooList = new Dictionary<string, Foo>();
fooList.Add("Foo Name", new Foo());
var item = fooList["Foo Name"];
0

List<T> Dictionary<TKey, TValue>.

Dictionary<string, Foo> fooDictionary = new Dictionary<string, Foo>();

fooDictionary.Add("Foo Name", new Foo());
Foo myFoo = fooDictionary["Foo Name"];
0

,

    public datat-type this[int x]
    {
    get{
    //getter code
    }
    set{
    //Setter code
    }
    }
    public data-type this[string x]
    {
    get{
    //setter code
    }
    set{
    //setter doe
    }
    }
0

List.Find . , , , () . Foo.

:

List<Foo> fooList = new List<Foo>; 
Foo item = fooList["Foo Name"] 

//Find Using Inline 
Foo foo = fooList.Find(delegate(Foo f) { return f.Name == "Foo Name"; });
0
source

All Articles