如何更换" - "在LINQ中列为空时使用空格

时间:2017-07-12 12:43:38

标签: c# linq select string-concatenation

这里我在Linq查询下面有员工持续时间列。如何删除" - "当EndDatevar query = from r in db.Employee select new { Name = r.Name, EmployeeDuration = r.StartDate +" - "+ r.EndDate } 为空时。我想" - "只有当两者都不为空时。

| id | in | value | valueMax |
| 1  | 1  |  10   |  25      |
| 1  | 2  |  11   |  25      |
| 1  | 3  |  12   |  25      |
| 2  | 1  |  20   |  35      |
| 2  | 2  |  21   |  35      |
| 2  | 3  |  22   |  35      |

4 个答案:

答案 0 :(得分:5)

您可以使用条件运算符。

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 - ?

答案 1 :(得分:0)

EmployeeDuration = r.StartDate != null && r.EndDate != null ? r.StartDate + " - " + r.EndDate : String.Empty;

答案 2 :(得分:0)

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
            }

答案 3 :(得分:0)

这样的事情:

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
    };