First, I would reiterate what @TnTinMn has said: Try to wean off Microsoft.VisualBasic. It's OK to pick-and-choose whatever's useful there - in which case be very thoughtful and intentional (e.g. even C#'ers like InputBox a lot! - What is the C# version of VB.net's InputDialog?). However, VB today has so many nicer and better ways of getting things done.
The major flaw of ye olde IIf()
is that it is just some function, which means every parameter gets executed no matter the condition. That makes it barely useful, even in VB6/VBA, because you just can't avoid any run-time-error/exception that you know is going to happen per the condition. If()
on the other hand is an actual operator, and it delivers exactly what everyone wants - a way to carefully prune what gets executed in an expression without having to write a specialized function.
So the easy answer is just to replace IIf()
with If()
and be pretty much done with it:
Dim sMatchedBranches = If(Not IsNothing(oUser.UserBranches),
oUser.UserBranches.Select(Function(z) String.Format("{0} - BranchCode", z.BranchCode)), "")
And one might feel that's good enough. But there's three other tricks in VB to make things nicer yet.
The first is the ?
operator. This is a handy way to say something like If(oUser.UserBranches Is Nothing, Nothing, oUser.UserBranches.Select(Function(z) String.Format("{0} - BranchCode", z.BranchCode)))
, except with ?
it's now like this:
oUser.UserBranches?.Select(Function(z) String.Format("{0} - BranchCode", z.BranchCode))
The second trick is string interpolation, in the format of $"{myVar}"
. Instead of String.Format("{0} - BranchCode", z.BranchCode)
, it can now be:
$"{z.BranchCode} - BranchCode"
The third trick is about If()
: If you give it two parameters, it will give a very handy way of dealing with Nothing
. If(x,y)
means if x
is not Nothing
, return x
, otherwise return y
. (If(x,y)
means the same as x ?? y
in C#.)
Putting it all together:
Dim sMatchedBranches = If(oUser.UserBranches?.Select(Function(z) $"{z.BranchCode} - BranchCode"), "")