开发者

Having an object in a list know statistical information about that list

开发者 https://www.devze.com 2022-12-10 01:50 出处:网络
For the sake of argument I have Person Objects public class Person { public int Age { get; set; } public string Name { get; set; }

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:

  1. Calculate the average (.Average()-Extension method)
  2. Compute percentual distance to the average age
  3. 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

0

精彩评论

暂无评论...
验证码 换一张
取 消