我正在尝试检查某个范围内的人 - 让lb-lowerbound和ub-upper对应于例如lb = 18和ub = 24的年龄组,这意味着我试图过滤掉年龄在18到24岁之间的人。另外,数据库中出生日期的日期时间字段可以为空。我有这段代码 -
var users=from e in employee
where e.DOB.HasValue && ((DateTime.Now.Year - e.DOB.Value.Year)) >= lb)
&& ((DateTime.Now.Year - e.DOB.Value.Year) <= ub)
select e;
但这只是检查当年我如何使用月份并找出实际年龄并根据年龄筛选出用户?感谢大家的帮助。
答案 0 :(得分:10)
首先,该查询在一年中的时间方面是不正确的 - 例如,您可能是17岁,仍然算作18岁 - 截至今天(2011年1月17日),1993年出生的人数很少。此外,它多次计算DateTime.Now
,这意味着查询执行时年份可能会有所不同。
最后,如果您只有一个where
子句且select
子句是无操作,则使用扩展方法语法而不是查询表达式通常更简单。
我建议:
DateTime today = DateTime.Today;
DateTime min = today.AddYears(-ub);
DateTime max = today.AddYears(-lb);
var years = employee.Where(e => e.DOB != null && e.DOB >= min && e.DOB <= max);
编辑:为了更清楚,对于最大年龄(比方说)10,这意味着你想要排除出生日期 11 年前或以上的任何人,所以你写道:
DateTime today = DateTime.Today;
DateTime min = today.AddYears(-(maxAge + 1));
DateTime max = today.AddYears(-minAge);
var years = employee.Where(e => e.DOB != null && e.DOB > min && e.DOB <= max);
答案 1 :(得分:2)
这应该可以解决问题(未经测试):
var users = from e in employee
where e.DOB.HasValue && (DateTime.Today - e.DOB.Value.Date) >= min.Date
&& e.DOB.Date <= max.Date
select e;
答案 2 :(得分:0)
为什么不仅仅创建一个年龄模型并比较年龄而不是搞乱日期?
public class Age
{
private readonly DateTime dob;
public Age(DateTime dob)
{
this.dob = dob;
}
public int Value
{
get { return this.CalculateAge(this.dob); }
}
private int CalculateAge(DateTime dob)
{
DateTime today = DateTime.Today;
int age = today.Year - dob.Year;
if (today.Month < dob.Month || (today.Month == dob.Month && today.Day < dob.Day))
age--;
return age;
}
}
然后使用linq查询最小和最大年龄。您可以将Age作为属性纳入员工模型。建立员工时,您可以致电使用Age类来计算年龄。您的linq会看起来像这样:
var years = employee.Where(e.Age >= min && e.Age <= max);