0

我是 LINQ 的初学者。我想执行一些条件操作,如下所示,

(from emp in Employees 
let DOB=emp.BirthDate.GetValueOrDefault()
let year=DOB.Year
let month=DOB.Month
let EmpAgeInYearsToday=DateTime.Now.Year-year
let EmpAgeInMonthToday=DateTime.Now.Month-month
let temp_year=(EmpAgeInYearsToday-1)
let ExactNoOfMonths_temp=EmpAgeInMonthToday<0?temp_year:EmpAgeInMonthToday
let ExactNoOfMonths=EmpAgeInMonthToday<0?EmpAgeInMonthToday+12&temp_year:EmpAgeInMonthToday
select new{emp.EmployeeID,DOB,
EmployeeAgeToday=EmpAgeInYearsToday+" Years "+ExactNoOfMonths+" Months ").Dump();

这里,

让 ExactNoOfMonths=EmpAgeInMonthToday<0?EmpAgeInMonthToday+12&temp_year:EmpAgeInMonthToday

这部分不起作用。单独 & 左侧的表达式正在执行。我想执行这两个操作。如何做到这一点?条件​​满足时如何进行多次操作?有没有其他替代方法可以做到这一点?

4

1 回答 1

0

我想你的意思是这样的:

ExactNoOfMonths = EmpAgeInMonthToday < 0 ?
                      EmpAgeInMonthToday + 12 :
                      temp_year ? 
                          EmpAgeInMonthToday :
                          somethingElse

但应该有第三个值 ( somethingElse) 用于 whenEmpAgeInMonthToday >= 0temp_year = false

编辑

你想要的其实很复杂。你最好只在内存中获取出生日期并用纯 C# 进行计算。

This CodeProject link gives a possible approach. As you'll see you can't avoid leap years and month lengths: the difference between Feb 28 and Mar 28 is 1 month in a normal year, 1 month and 1 day in a leap year.

于 2012-09-06T10:48:47.547 回答