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

后端 未结 4 2018
你的背包
你的背包 2021-01-18 00:45

Let\'s say I have this class:

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

And then I have a list of Person\'s.



        
4条回答
  •  暖寄归人
    2021-01-18 01:09

    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)
    

提交回复
热议问题