亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算年齡范圍內的人群

計算年齡范圍內的人群

C#
森欄 2022-12-04 13:19:56
我有一個小方法來獲取特定年齡范圍內的成員數量。該范圍應該包括兩端,即如果我調用CountSelection(memberList, 16, 19)(memberLista在哪里List<Member>),我希望將 16、17、18 和 19 歲的成員人數加在一起:private int CountSelection(List<Member> members, int minAge, int maxAge){    DateTime from = DateTime.Now.AddYears(minAge * -1);    DateTime to = DateTime.Now.AddYears(maxAge * -1);    return members.Count(m =>        m.DateBorn.Date <= from.Date &&         m.DateBorn.Date >= to.Date);}但是,我的方法不可靠 - 有時它會省略成員,我猜測出生日期何時落在范圍之間。在main方法中,我調用CountSelection()了幾次,每次調用的范圍都不一樣,理論上覆蓋所有年齡層。查詢應該是什么樣子才能保證所有成員都被計算在內?
查看完整描述

2 回答

?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

我發現了為什么我的方法失敗了。我只是從開始日期和結束日期中減去整年,得到的范圍看起來像這樣(日期格式 dd.mm.yyyy):


0-5 years - 11.04.2014-11.04.2019

6-12 years - 11.04.2007-11.04.2013

13-19 years - 11.04.2000-11.04.2006

20-26 years - 11.04.1993-11.04.1999

... and so on.

注意每個范圍之間將近一年的差距。


解決方案:


而不是像這樣設置起始日期:


DateTime from = DateTime.Now.Date.AddYears(-maxAge);

我當然必須再減去 1 年并增加 1 天:


DateTime from = DateTime.Now.Date.AddYears(-maxAge + 1).AddDays(1);

現在范圍看起來像這樣:


0-5 years - 12.04.2013-11.04.2019

6-12 years - 12.04.2006-11.04.2013

13-19 years - 12.04.1999-11.04.2006

20-26 years - 12.04.1992-11.04.1999

... and so on.

最終的工作方法如下所示:


private int CountSelection(List<Member> members, int minAge, int maxAge)

{

    DateTime from = compareDate.AddYears(-maxAge+1).AddDays(1);

    DateTime to = compareDate.AddYears(-minAge);

    return members.Count(m => 

        m.DateBorn >= from && 

        m.DateBorn <= to);

}


查看完整回答
反對 回復 2022-12-04
?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

使用具有唯一上限的范圍更容易:


private int CountSelection(List<Member> members, int minAge, int maxAgeExclusive)

{

    DateTime from = compareDate.AddYears(-maxAgeExclusive);

    DateTime to = compareDate.AddYears(-minAge);

    return members.Count(m => m.DateBorn > from && m.DateBorn <= to);

}

現在您的范圍在數學上將更加一致。


0-6 years

6-13 years

13-20 years

20-27 years

etc

然后可以在表示層的上限減一。


查看完整回答
反對 回復 2022-12-04
  • 2 回答
  • 0 關注
  • 147 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號