Dear Deer
Dear Deer

Reputation: 543

Using ternary operator with return

Why I can't shortcut this :

if (await query.AnyAsync())
{
     return new ObjectResult(query);
}
     else
{
     return NotFound();
}

to this :

await query.AnyAsync() ? return new ObjectResult(query) : return NotFound();

How can I shortcut this ?

Upvotes: 2

Views: 4443

Answers (2)

nvoigt
nvoigt

Reputation: 77364

This is not exactly what you asked for, but anyway:

These lines are wrong:

if (await query.AnyAsync())
{
     return new ObjectResult(query);
}

Either your query is already materialized, in which case it makes no sense to see if it has any entries asynchronously. Thhat would be overhead plain and simple. OR it is not materialized, in which case your Any call is useless, because it will only materialize it once then check if it has entries and then materialize it again for your result. That second call might as well contain no entries if something changes in your source between those calls. Best case is it's double the runtime for the same result.

So if you want to simplify and correct it:

var materialized = query.ToList();

if (materialized.Count != 0)
{
     return new ObjectResult(materialized);
}

return NotFound();

It does not get more simple. No need for a ternary operator here.

If you want a ternary operator, you will need to make sure it gets expressions of the same type, not statements (return 0; is a statement, 0 is an expression):

var materialized = query.ToList();

return (materialized.Count != 0)
    ? (IActionResult)new ObjectResult(materialized)
    : (IActionResult)NotFound();

Upvotes: 1

benjrb
benjrb

Reputation: 836

You're missing a cast. To use a conditional expression you need to cast them to the same return type e.g.

return await query.AnyAsync() ? (ActionResult)new ObjectResult(query) : (ActionResult)NotFound();

Upvotes: 7

Related Questions