-2

I have searched this topic but it always ends up showing results for TWO lists that need comparing.

How would I be able to compare specific properties of 2 or more objects that are within the same list?

For example in below sample code, how can I compare just the age value to find out which Person in the entire list is the youngest? Thanks!

public class Person
{
    private string name;
    private short age;


     public Person(string name, short age)
     {
         this.name = name;
         this.age = age;
     }

     public string Name
     {
         get { return name;  }
         set { name = value; }
     }

     public short Age
     {
         get { return age; }
         set { age = value; }
     }

}

List<Person> PersonList = new List<Person>();

PersonList.Add(new Person("John Smith", 35));
PersonList.Add(new Person("Jane Doe", 18));
PersonList.Add(new Person("Bill Lee", 28));
Programmer
  • 291
  • 1
  • 3
  • 14

1 Answers1

1

Sorting based on the Age properties and returning the first element:

Person the_youngest = PersonList.OrderBy(i => i.Age).ToList<Person>().First();

Also in place sort using Linq:

PersonList = PersonList.OrderBy(x => x.Age).ToList<Person>();
Rezaeimh7
  • 1,467
  • 2
  • 23
  • 40
  • For small number of items this is acceptably simple, but on larger items this order the whole list instead of simply scanning for the largest member which can take far more CPU and RAM. – Martheen Feb 02 '21 at 06:27