t_plusplus
t_plusplus

Reputation: 4209

C# Ternary Operator used in LINQ query

Is it possible to use the ternary operator to reflect this logic?

if (a = 1)
{
    somevalue = "hello";
} 
else if (a = 2)
{
    someValue = "world";
}
else if (a = 3)
{
    someValue = "hellWorld";
}

I am doing the following in a LINQ Query:

using (var data = new DAL())
{
    var result = data.Holidays.AsNoTracking()
                 .Where(x => x.RequesterId == userId)
                 .Select(x => new HolidayModel
                 {
                     HolidayId = x.HolidayId,
                     FromDate = x.FromDate,
                     ToDate = x.ToDate,
                     AuthorisationStatus = x.InternalHolidayStatus == 1 ?
                         HolidayAuthStatus.Pending :
                         HolidayAuthStatus.Rejected,
                     DateModified = x.ModifiedDate
                 }).ToList();

    return Json(result.ToDataSourceResult(request));
}

HolidayAuthStatus is an enum, which has three values in it (Pending (1), Authorised (2) and Rejected (3)); and I would like to reflect this in code when assigning the value of AuthorisationStatus.

Upvotes: 0

Views: 8184

Answers (2)

Anders Abel
Anders Abel

Reputation: 69260

Yes it's possible. I think it's hard to get the operator precedence right with the ternary operator, so I prefer using parantheses:

AuthorizationStatus = x.InternalHolidayStatus == 1 ?
    HolidayStatus.Pending :
    (x.InternalHolidayStatus == 2 ?
        HolidayStatus.Rejected : 
        (x.InternalHolidayStatus == 3 ?
            HolidayStatus.Authorized : 
            HolidayStatus.Invalid))

Since this is a mapping to an enum it's also a possibility to use a cast as @wodzik suggests, if it is possible and feasible to use the same values for the enum values as they are in the database.

To use that you will have to explictility assign values to the enums

public enum HolidayStatus
{
    Pending = 1,
    Rejected = 2,
    Authorized = 3
}

Then you can do:

AuthorizeStatus = (HolidayStatus)x.InternalHolidayStatus

Upvotes: 4

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

change to this

AuthorisationStatus = (HolidayAuthStatus)x.InternalHolidayStatus

if integer values for your HolidayAuthStatus match InternalHolidayStatus values it will work. Ternary operator here will look horible. If your status code doesn't match it's better to make function accepting int status and returning HolidayAuthStatus

HolidayAuthStatus GetStatus(int status)
{
    if(status == 1) return HolidayAuthStatus.Pending;
    if(status == 2) return HolidayAuthStatus.Authorised;
    if(status == 3) return HolidayAuthStatus.Rejected;
    return HolidayAuthStatus.Unknown; // for e.g.
}

and use it like:

AuthorisationStatus = GetStatus(x.InternalHolidayStatus)

EDIT:

as @James said method will work only in Linq-to-object not in Linq-to-entities

Upvotes: 4

Related Questions