C# “如何替换”-&引用;在LINQ中列为null时使用空空格
在这里,我有下面的Linq查询,其中有employee duration列。当C# “如何替换”-&引用;在LINQ中列为null时使用空空格,c#,linq,select,string-concatenation,C#,Linq,Select,String Concatenation,在这里,我有下面的Linq查询,其中有employee duration列。当StartDate或EndDate为空时,如何删除“-”。只有当两者都不为空时,我才需要“-” var query = from r in db.Employee select new { Name = r.Name, EmployeeDuration = r.StartDate +" - "+ r.En
StartDate
或EndDate
为空时,如何删除“-”。只有当两者都不为空时,我才需要“-”
var query = from r in db.Employee
select new
{
Name = r.Name,
EmployeeDuration = r.StartDate +" - "+ r.EndDate
}
可以使用条件运算符
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
}
输出
或者另一种方法就是这样
var query = from r in db.Employee
select new
{
Name = r.Name,
EmployeeDuration =
(r.StartDate ?? "?") +
" - " +
(r.EndDate ?? "?")
}
输出
可以使用条件运算符
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
}
输出
或者另一种方法就是这样
var query = from r in db.Employee
select new
{
Name = r.Name,
EmployeeDuration =
(r.StartDate ?? "?") +
" - " +
(r.EndDate ?? "?")
}
输出
大概是这样的:
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
};
大概是这样的:
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
};
可以有一个没有开始日期的结束日期吗?两个日期也可以为空吗?在这种情况下,预期的输出是什么?是否可以有一个没有开始日期的结束日期?两个日期是否都可以为空?在这种情况下,预期的输出是什么?您可以将最后一行简化为
r.StartDate??r、 EndDate
您可以将最后一行简化为r.StartDate??r、 结束日期
@DavidG哦,我明白了。已修复。空字符串仍然需要一个值,例如:$“{employee.StartDate??employee.EndDate}”
@DavidG哦,我明白了。已修复。空字符串仍然需要一个值,例如:$“{employee.StartDate??employee.EndDate}”
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
};