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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With