Recognizing an object is like an index, but by name in C #

I have classes, father and child (for example)

Fragment 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'm trying to do something like this

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

I am now, its wrong, I need to implement something in the Child Class, I tried this

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

But that does not work.

How can I implement this function for my Child class?

+3
source share
5 answers

Or you can configure it as follows:

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 what you want.

+4
source

A List<T>does not have a row indexer; you can add it to the class Father, but use will be:

var child = parent["Fred"];

(no.Children)

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

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

, .

IMO, ():

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

:

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

:

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

( ). .

+1

Children List OrderedDictionary, , . , , .

+1

Source: https://habr.com/ru/post/1779650/


All Articles