For the sake of argument I have Person Objects
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
I need to have a List or something similar where each person can tell if they are older or younger than the average age. (Ideally I want to say top 10% and bottom 10%) but I will settle for over under median.
Is there a way to do this?
List<Person> people = new List<Person>();
//Fill People
foreach(var person in people)
{
if (person.TopTenPercent)
{
Console.WriteLine(person.Name);
}
}
Th开发者_运维问答anks Mark
Really you should have the list or something else encapsulate this information (SRP and all that). So say that you have
class People : IEnumerable<Person> {
public double MedianAge { get; }
// etc.
}
Then you would say
foreach(var person in people.Where(p => p.Age >= people.MedianAge)) {
Console.WriteLine(person.Name);
}
For the general case you can have a PercentileAge
method on your People
class:
public double PercentileAge(double percentile)
You can use Linq:
- Calculate the average (
.Average()
-Extension method) - Compute percentual distance to the average age
- Select specified range
Make a personlist that adds itself as a reference to the person so that the person can query the list's contents/stats
精彩评论