以检查LINQ年龄过滤器最短的路? [英] Shortest way to check for age filter in LINQ?

查看:73
本文介绍了以检查LINQ年龄过滤器最短的路?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图来检查的人在一定范围内 - 让相应的如LB-下界和UB-上限

I am trying to check for people in a certain range - let lb-lowerbound and ub-upper bound corresponding for e.g. age group with lb=18 and ub=24 meaning I am trying to filter out the people aged between 18 and 24.Also Datetime field in database for date of birth is nullable.I have this code -

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;



不过这只是与去年检查我怎么使用一个月,并找出实际年龄和根据自己的年龄筛选出用户?感谢大家的帮助。

but this is only checks with the year how do I use the month and find out the actual age and filter out the users according to their age ? Thanks everyone for their help.

推荐答案

首先,该查询年内是在时间方面不正确 - 你可能是17仍算作18,例如 - 1993年出生的人很少是18今日(2011年1月17日)的。此外,它的计算 DateTime.Now 多次,这意味着今年可能会有所不同的而执行查询时

Firstly, that query is incorrect in terms of times during the year - you could be 17 and still counted as 18, for example - very few people born in 1993 are 18 as of today (January 17th 2011). Also, it's computing DateTime.Now multiple times, which means the year could vary while the query is executing.

最后,如果你刚刚得到了一个其中,条款和你的选择子句,无操作,这是一般简单的使用扩展方法语法,而不是一个查询表达式

Finally, if you've just got a single where clause and your select clause is a no-op, it's generally simpler to use the extension method syntax rather than a query expression.

我建议:

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 的年前或更多,所以你写的:

To be clearer, for a maximum age of (say) 10, that means you want to exclude anyone whose date of birth was 11 years ago or more, so you'd write:

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);

这篇关于以检查LINQ年龄过滤器最短的路?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆