0

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
            }
NtFreX
  • 10,379
  • 2
  • 43
  • 63
user1030181
  • 1,995
  • 5
  • 26
  • 56

4 Answers4

5

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 - ?
NtFreX
  • 10,379
  • 2
  • 43
  • 63
0
EmployeeDuration = r.StartDate != null && r.EndDate != null ? r.StartDate + " - " + r.EndDate : String.Empty;
Dmitry
  • 512
  • 7
  • 15
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
            }
Mark Shevchenko
  • 7,937
  • 1
  • 25
  • 29
0

Something like this:

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
    };
Pablo notPicasso
  • 3,031
  • 3
  • 17
  • 22