Home Ask Login Register

Developers Planet

Your answer is one click away!

Jose Luis 2 weeks ago

Create list<objects> in C#

Trying to create a class of customs objects like next:

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

// Then create the list class:

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

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

The idea is to create the list of objects, then access the getAge() function directly. I know is possible to just create list, but in order to simplify code I would like to create a custom list. Thanks

Answers


Yair Halberstadt 2 weeks ago

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;       
}

Post Status

Asked in 2 weeks ago
Viewed 2,643 times
Voted 13
Answered 1 times

Search




Leave an answer


Quote of the day: live life