-3

I am trying to create a class like this:

public class person
{
    public string name { get; set;}
    public int age  { get; set;}
}

and create a class which is basically a list of the class above:

public class PersonList : List<person>
{
    public PersonList()
    { 
    }

    public int getAge(string name)
    { 
        foreach( string s n this)
        {
            if ( s == name)
                return age;
        }
    }

My goal is to have simple function named GetAge() so I get the the age by name of any person object in my list. I know it is possible to just create a list, but I want a modular code.

Jose Luis
  • 7
  • 1

2 Answers2

2
public int getAge(string name)
{ 
     return this.First(x=>x.name==name).age;       
}

This will throw an error if person not found.

To return -1 when person is not found:

public int getAge(string name)
{ 
     return this.FirstOrDefault(x=>x.name==name)?.age??-1;       
}
Yair Halberstadt
  • 5,733
  • 28
  • 60
0

I think you must consider that a name can be repeated in a list so you arbitrarily would be getting the first one, in the sample below you have two options.

public class person
    {
        public string name { get; set; }
        public int age { get; set; }
    }
    public class PersonList : List<person>
    {
        public int getAge(string name)
        {
            return this.FirstOrDefault(x => x.name == name)?.age ?? -1;
        }
        public int[] getAge2(string name)
        {
            return this.Where(x => x.name == name).Select(x=>x.age).ToArray();
        }
    }

And you will get a list of ages in case the name is repeated, console code below

static void Main(string[] args)
        {
            PersonList listOfPerson = new PersonList();
            listOfPerson.Add(new person() { age = 25, name = "jhon" });
            listOfPerson.Add(new person() { age = 26, name = "jhon" });
            listOfPerson.Add(new person() { age = 21, name = "homer" });
            listOfPerson.Add(new person() { age = 22, name = "bill" });
            listOfPerson.Add(new person() { age = 27, name = "jhon" });
            listOfPerson.Add(new person() { age = 22, name = "andrew" });

            foreach (var item in listOfPerson.getAge2("jhond"))
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
Victor Hugo Terceros
  • 2,969
  • 3
  • 18
  • 31