开发者

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

开发者 https://www.devze.com 2023-01-29 18:28 出处:网络
I have to classes, Father and Child (by example) A snippet of my开发者_Python百科 implementation Class Father.cs

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

A snippet of my开发者_Python百科 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?


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) {...}


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.


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!


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消