我是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(身份证号码是2)
36-45(ID为3)
46-55(身份证号码是4)
55及以上(ID为5)
例如,如果成员DOB是1990-01-15,则他属于agegroup 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来更新数据库中的所有行? 谢谢你的帮助!
答案 0 :(得分:1)
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
}
答案 1 :(得分:1)
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();