Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

list

Let's 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 alot of random persons. How do I query the list to get the person with the lowest ID? The objects in the list is in a random order so the person with the lowest ID might not be the very first element. Can I achieve this without sorting the list first?

like image 543
Dave Avatar asked Nov 05 '14 10:11

Dave


3 Answers

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;
}
like image 170
Hamid Pourjam Avatar answered Nov 13 '22 23:11

Hamid Pourjam


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);
like image 41
Selman Genç Avatar answered Nov 13 '22 23:11

Selman Genç


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)
like image 33
galenus Avatar answered Nov 13 '22 23:11

galenus