如何在 LINQ 中列为空时用空 space 替换“-”
How to replace "-" with empty space when columns are null in LINQ
这里我有下面的 Linq 查询,其中有员工持续时间列。当 StartDate
或 EndDate
为空时,如何删除“-”。只有当两者都不为空时,我才想要“-”。
var query = from r in db.Employee
select new
{
Name = r.Name,
EmployeeDuration = r.StartDate +" - "+ r.EndDate
}
EmployeeDuration = r.StartDate != null && r.EndDate != null ? r.StartDate + " - " + r.EndDate : String.Empty;
您可以使用条件运算符。
var query = from r in db.Employee
select new
{
Name = r.Name,
EmployeeDuration = r.StartDate != null && r.EndDate != null
? r.StartDate + " - " + r.EndDate
: r.StartDate ?? r.EndDate
}
输出
When nothing is null = 18.01.2017 18:00 - 18.01.2017 19:00
When StartDate is null = 18.01.2017 19:00
When EndDate is null = 18.01.2017 18:00
或者另一种方法是这样。
var query = from r in db.Employee
select new
{
Name = r.Name,
EmployeeDuration =
(r.StartDate ?? "?") +
" - " +
(r.EndDate ?? "?")
}
输出
When nothing is null = 18.01.2017 18:00 - 18.01.2017 19:00
When StartDate is null = ? - 18.01.2017 19:00
When EndDate is null = 18.01.2017 18:00 - ?
var query = from employee in db.Employee
let areDatesNull = employee.StartDate == null
|| employee.EndDate == null
let duration = areDatesNull
? ""
: $"{employee.StartDate} - {employee.EndDate}"
select new
{
Name = employee.Name,
EmployeeDuration = duration
}
像这样:
var query = from r in db.Employee
select new
{
Name = r.Name
,
EmployeeDuration =
r.StartDate + ((r.StartDate == null || r.EndDate == null) ? string.Empty : " - ") + r.EndDate
};
这里我有下面的 Linq 查询,其中有员工持续时间列。当 StartDate
或 EndDate
为空时,如何删除“-”。只有当两者都不为空时,我才想要“-”。
var query = from r in db.Employee
select new
{
Name = r.Name,
EmployeeDuration = r.StartDate +" - "+ r.EndDate
}
EmployeeDuration = r.StartDate != null && r.EndDate != null ? r.StartDate + " - " + r.EndDate : String.Empty;
您可以使用条件运算符。
var query = from r in db.Employee
select new
{
Name = r.Name,
EmployeeDuration = r.StartDate != null && r.EndDate != null
? r.StartDate + " - " + r.EndDate
: r.StartDate ?? r.EndDate
}
输出
When nothing is null = 18.01.2017 18:00 - 18.01.2017 19:00
When StartDate is null = 18.01.2017 19:00
When EndDate is null = 18.01.2017 18:00
或者另一种方法是这样。
var query = from r in db.Employee
select new
{
Name = r.Name,
EmployeeDuration =
(r.StartDate ?? "?") +
" - " +
(r.EndDate ?? "?")
}
输出
When nothing is null = 18.01.2017 18:00 - 18.01.2017 19:00
When StartDate is null = ? - 18.01.2017 19:00
When EndDate is null = 18.01.2017 18:00 - ?
var query = from employee in db.Employee
let areDatesNull = employee.StartDate == null
|| employee.EndDate == null
let duration = areDatesNull
? ""
: $"{employee.StartDate} - {employee.EndDate}"
select new
{
Name = employee.Name,
EmployeeDuration = duration
}
像这样:
var query = from r in db.Employee
select new
{
Name = r.Name
,
EmployeeDuration =
r.StartDate + ((r.StartDate == null || r.EndDate == null) ? string.Empty : " - ") + r.EndDate
};