[英]How to Write LINQ with multiple condition
我是LINQ的新手,我對如何在LINQ中編寫IF ELSE感到困惑。
我創建的當前LINQ是:
lstRecord = (from a in lstPerson
select new GeneralCommonFunctions.MemberDetailSumary
{
AgeGroupId = a.AgeGroup_id!=null? a.AgeGroup_id.Value: 0,
AgeGroupText = a.Agegroup!=null?a.Agegroup.Description: "",
}).ToList();
現在,我想從列表中獲取DOB並根據今天的日期計算當前年齡,然后將其分類為年齡組(當前版本直接從數據庫中獲取年齡組)。
可用年齡段為:
25以下(ID為1)
26-35(ID為2)
36-45(ID為3)
46-55(ID為4)
55以上(ID為5)
例如,如果成員DOB是1990-01-15,則他屬於年齡組2。如果成員DOB是1970-12-20,則他屬於年齡組4。
我陷入了這種編碼:
lstRecord = (from a in lstPerson
select new GeneralCommonFunctions.MemberDetailSumary
{
Age = DateTimeUtility.GetCurrentAge(a.Dob),
//I dont know how to continue in this part, my idea is if the age is 0-25, the agegroup_id is 1, if the age is 30, the agegroup_id is 2.
}).ToList();
你們當中有人可以幫助我嗎? 謝謝 !
更新:
單擊按鈕時,我有一個使用LINQ更新所有行的想法。 例如,如果用戶單擊一個按鈕,則系統將檢查每個人的DOB,然后更新數據庫中的年齡組。
例如,如果人A DOB為1990-01-01,則其年齡組將自動更新為2,如果人B DOB為1970-05-15,則其年齡組將更新為4。
如何編寫一個linq來更新數據庫中的所有行? 謝謝您的幫助!
lstRecord = (from a in lstPerson
select new GeneralCommonFunctions.MemberDetailSumary
{
Age = DateTimeUtility.GetCurrentAge(a.Dob),
AgeGroupID = GetAgeGroup(a.Dob);
}).ToList();
您可以創建方法GetAgeGroup
在其中您將給出當前的出生日期。 根據您的解釋, a.Dob
是DateTime
。 之后,您要計算人員的年齡並輸入正確的AgeGroupID
public int GetAgeGroup(DateTime birthYear)
{
//here you can reuse your method DateTimeUtility.GetCurrentAge(a.Dob),
// I just wrote the logic because I'm not sure if it is correct.
int age= DateTime.Now.Years - birthYear.Years;
if (birthYear > DateTime.Now.AddYears(-years))
age--;
if(age<=25)
return 1;
else if( age> 25 && age<=35)
return 2;
else if(age> 35 && age<=45)
return 3;
else if(age> 45 && age<= 55)
return 4;
else if(age> 55)
return 5
else
return -1; // this will represent invalid age
}
lstRecord = (from a in lstPerson
select new GeneralCommonFunctions.MemberDetailSumary
{
Age = DateTimeUtility.GetCurrentAge(a.Dob),
}).Select(t=>new GeneralCommonFunctions.MemberDetailSumary{
Age=t.Age,
AgeGroupID = t.Age<=25?1:t.Age<=35?2:t.Age<=45?3:t.Age<=55?4:5,
}).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.