Bora
Bora

Reputation: 127

Using ternary operation without else in linq?

I need to know how do i use ternary operator without else. In the example I need to check 2 criterias (cityId != null) && (cityId != 0). I cannot use normal if conditions. So if it doesn't happen i want to list all titles. I don't want to show else condition is x.ProvinceId == 15

public JsonResult mt(int? cityId)
        {
            var getCities = locationRepository.Get(null).Where(x => ( (cityId != null) && (cityId != 0) ? x.ProvinceId == cityId : x.ProvinceId == 15  )).Select(x=>x.Title);

            return Json(new { items = getCities }, JsonRequestBehavior.AllowGet);
        }

Upvotes: 0

Views: 1695

Answers (1)

Rune FS
Rune FS

Reputation: 21742

The conditional operator is a ternary operator, meaning it accepts three operands. So omitting one is like omitting the second operand of an addition.

However you can simply reformat it as one condition

Depending on what should actually happen if the condition is not met. This will accept all that does not meet the condition you have

x => (cityId ?? 0) == 0 || x.ProvinceId == cityId

Upvotes: 1

Related Questions