Find the item with the lowest property value in the list.

Say I have this class:

class Person {
   public int ID;
   public string Name;
}

And then I have a list of Person's.

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

Which is filled with a lot of random faces. How to request a list to get the person with the lowest ID? The objects in the list are in random order, so the person with the smallest identifier may not be the very first element. Can I achieve this without sorting the list first?

+4
source share
3 answers

this does not sort the list and simply repeats the list once.

Person minIdPerson = persons[0];
foreach (var person in persons)
{
    if (person.ID < minIdPerson.ID)
        minIdPerson = person;
}
+6
source

You can use the MinBymethod from the More Linq library:

var person = persons.MinBy(x => x.ID);

, min, ID:

var minID = person.Min(x => x.ID);
var person = persons.First(x => x.ID == minID);
+3

Use the MIN method for LINQ:

persons.Min(p => p.ID)

EDIT:

My bad, previous method returns only the lowest identifier, so if you want to use only LINQ built-in methods, you are here:

persons.Aggregate(
    (personWithMinID, currentPerson) =>
        currentPerson.ID <= personWithMinID.ID ? currentPerson : personWithMinID)
+2
source

All Articles