使用LINQ按类别返回Ages列表

时间:2017-04-11 13:17:20

标签: c# linq linq-to-sql

因此,我的目标是显示一个饼图,其中包含按年龄分类的员工细分。理想情况下,我希望它在5年内增加,所以:15-19,20-24,25-29一直到65-69。虽然10-19,20-29等也很有用。

所有其他代码都没问题,但是我的查询已关闭,因为它几乎每个年龄段都会返回,甚至是多个年龄段的实例(即我有4个28的计数)

代码如下。非常感谢,谢谢。

//Employee Age Categories 
    public IEnumerable<KeyValuePair<int, int>> EmployeeAges()
    {
        using (var conn = Databases.HR)
        {
            var res =
                conn.Query<Employee>("SELECT EmployeeId,FirstName,Surname,DateOfBirth FROM EmployeeDetails")
                    .ToList();

            return from e in res
                       //get the difference in years since the birthdate
                   let years = DateTime.Now.Year - e.DateOfBirth?.Year
                   //get the date of the birthday this year
                   let birthdayThisYear = years.HasValue ? e.DateOfBirth?.AddYears(years.Value) : null as DateTime?

                   let age = birthdayThisYear > DateTime.Now ? years - 1 : years
                   where years != null
                   select new KeyValuePair<int, int>
                       (
                       //if the birthday hasn't passed yet this year we need years - 1
                       age.Value,
                       15 + (((int)(age - 15) / 4) * 4)
                       );

        }
    }

1 个答案:

答案 0 :(得分:2)

首先,我不会混合查询和年龄计算。您可以将age属性添加到employee类(它也可以是接受当前日期甚至是独立帮助方法的方法):

 public int? Age
 {
     get
     {
         if (!DateOfBirth.HasValue)
            return null;

         var today = DateTime.Now;
         int age = today.Year - birthdate.Value.Year;
         if (birthdate.Value > today.AddYears(-age))
            age--;

         return age;
     }
 }

现在查询:

from e in res
where e.DateOfBirth.HasValue
group e by e.Age.Value / 5 into g
orderby g.Key
select new {
   From = g.Key * 5,
   To = g.Key * 5 + 4,
   Count = g.Count()
};

E.g。如果您的雇员有以下出生日期:

[
  "1984-05-01T00:00:00",
  "1985-02-10T00:00:00",
  "1986-12-31T00:00:00",
  "1991-01-07T00:00:00",
  null,
  "1999-06-02T00:00:00",
  "2001-01-01T00:00:00",
  "1970-01-01T00:00:00"
]

输出

[
  { "From": 15, "To": 19, "Count": 2 },
  { "From": 25, "To": 29, "Count": 1 },
  { "From": 30, "To": 34, "Count": 3 },
  { "From": 45, "To": 49, "Count": 1 }
]