Find the item with the lowest value of a property within a list

this is without sorting the list and just iterates the list once.

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

You can use MinBy method from More Linq library:

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

If you can't use a third party library you can get the min ID first and then get the person that has the min ID:

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

Use the Min extension method of LINQ:

persons.Min(p => p.ID)

EDIT:

My bad, the previous method returns only the lowest ID, so in case you'd like to use only built-in LINQ methods, here you go:

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

Tags:

C#

.Net

List