Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select highest Age where Age is closest to a number

Tags:

c#

.net

linq

Think I have been looking at my code too much.

But my problems is that I have a unordered list and I need to select the object with the highest number closes to or equals an input.

I have created this little sample to illustrate what I trying to do.

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

var persons = new List<Person>
{
    new Person {Age = 10, Name = "Aaron"},
    new Person {Age = 15, Name = "Alice"},
    new Person {Age = 20, Name = "John"},
    new Person {Age = 22, Name = "Bob"},
    new Person {Age = 24, Name = "Malcom"}
};

int i = 17; //should return 'Alice 15'    
int y = 22; //should return 'Bob 22
like image 916
gulbaek Avatar asked Dec 12 '22 03:12

gulbaek


1 Answers

var person = persons.Where(p => p.Age <= input).OrderByDecending(p => p.Age).First();

This first excludes the ones that are greater than input (your i or y). Then starts to sort them, then it just takes the first result.

like image 92
Daniel A. White Avatar answered Jan 31 '23 09:01

Daniel A. White