Search code examples
c#linqselectstring-concatenation

How to replace "-" with empty space when columns are null in LINQ


Here I am having below Linq query which has employee duration column. How can I remove "-" when StartDate or EndDate is null. I want "-" only when both are not null.

var query = from r in db.Employee 
            select new 
            {
                Name = r.Name,
                EmployeeDuration = r.StartDate +" - "+ r.EndDate
            }

Solution

  • You could use a conditional operator.

    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
            }
    

    Output

    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
    

    Or another approach would be this.

    var query = from r in db.Employee 
            select new 
            {
                Name = r.Name,
                EmployeeDuration = 
                    (r.StartDate ?? "?") +
                    " - " +
                    (r.EndDate ?? "?")
            }
    

    Output

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