Single line if statement with 2 actions

2020-05-14 07:30发布

I'd like to do a single line if statement with more than 1 action.

Default is this:

(if) ? then : else

userType = (user.Type == 0) ? "Admin" : "User";

But I don't need an "else" only, I need an "else if"

like that in multi line:

if (user.Type == 0)
    userType = "Admin" 
else if (user.Type == 1)
    userType = "User"
else if (user.Type == 2)
    userType = "Employee"

Is there a possibility for that in single line?

3条回答
SAY GOODBYE
2楼-- · 2020-05-14 08:25

Sounds like you really want a Dictionary<int, string> or possibly a switch statement...

You can do it with the conditional operator though:

userType = user.Type == 0 ? "Admin"
         : user.Type == 1 ? "User"
         : user.Type == 2 ? "Employee"
         : "The default you didn't specify";

While you could put that in one line, I'd strongly urge you not to.

I would normally only do this for different conditions though - not just several different possible values, which is better handled in a map.

查看更多
▲ chillily
3楼-- · 2020-05-14 08:26

You can write that in single line, but it's not something that someone would be able to read. Keep it like you already wrote it, it's already beautiful by itself.

If you have too much if/else constructs, you may think about using of different datastructures, like Dictionaries (to look up keys) or Collection (to run conditional LINQ queries on it)

查看更多
【Aperson】
4楼-- · 2020-05-14 08:29
userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";

should do the trick.

查看更多
登录 后发表回答