Thursday, April 12, 2012

Select highest Age where Age is closest to a number

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




1 comment:

  1. 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.

    link|improve this answer

    ReplyDelete