Ewerton
Ewerton

Reputation: 4523

Acessing object like by Index, but by name in C#

I have to classes, Father and Child (by example)

A snippet of my implementation

Class Father.cs

public class Father
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Child> Children { get; set; }

    public Father()
    {
    }
}

Class Child.cs

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Child()
    {
    }

}

I'am trying to do something like this

        Father f = new Father();
        f.Children[0]; // ok
        f.Children[1]; // ok
        f.Children["John"]; // Duh!

I now, its wrong, i need to implement something in Child Class, i tryed this

    public Child this[string name]
    {
        get
        {
            return this;
        }
    }

But this doesnt work.

How can i implement this feature for my class Child?

Upvotes: 3

Views: 6734

Answers (5)

Marc Gravell
Marc Gravell

Reputation: 1062820

A List<T> doesn't have a string indexer; you could add one to the Father class, but the usage will be:

var child = parent["Fred"];

(no .Children)

For the indexer itself: Try (in the indexer):

return Children.FirstOrDefault(c=>c.Name==name);

To get an indexer on the list itself, you would have to create a custom list type and add the indexer there.

IMO, a method may be clearer (on Father):

public Child GetChildByName(string name) {...}

Upvotes: 6

Rangoric
Rangoric

Reputation: 2799

Or you can set it up like this:

public class Father
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Children Children { get; set; }

    public Father()
    {
    }
}
public class Children : List<Child>
{
    public Child this[string name]
    {
        get
        {
            return this.FirstOrDefault(tTemp => tTemp.Name == name);
        }
    }
}
public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Child()
    {
    }
}

Then you call it how you want.

Upvotes: 4

You could make the Children List into an OrderedDictionary so that you can reference it by index or key and then add the objects with the name as the key. Just so you know though, any of these options can run into issues if you have multiple children with the same name.

Upvotes: 1

decyclone
decyclone

Reputation: 30830

In father class, you could write following code:

public Child this[string name]
{
    get
    {
        return Children.Where(c => c.Name == name);
    }
}

and use it like:

    Father f = new Father();
    f.Children[0]; // ok
    f.Children[1]; // ok
    f["John"]; // ok!

Upvotes: 4

DarrellNorton
DarrellNorton

Reputation: 4651

You are treating the List of Children like a Dictionary (Dictionaries can be accessed by key). Just change your List to a Dictionary and set the string to be the Child's name.

Upvotes: 1

Related Questions