'Conditional logic in new SelectListItem in ASP.NET Core 6 MVC

I want to set the text value of a SelectListItem.

What's the easiest way? I've tried variations of the following with no luck.

 public IActionResult Upsert(int? id)
 {
    RegistrationVM registrationVM = new()
    {
        Registration = new(),
        AttendedList = _unitOfWork.Registration.GetAll().Select(i => new SelectListItem
        {
            if (i.ATTENDED == 0)
            {
                Text = "No"
            }
            else
            {
                Text = "Yes"
            },
            Value = i.ATTENDED.ToString()
        })
    };
}


Solution 1:[1]

You need an expression that resolves to a value, rather than a set of statements that form a control flow block. The simplest is, in my opinion, a ternary:

    AttendedList = _unitOfWork.Registration.GetAll().Select(i => new SelectListItem
    {
        Text = i.ATTENDED == 0 ? "No" : "Yes",
        Value = i.ATTENDED.ToString()
    })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caius Jard