Lou
Lou

Reputation: 2509

Is there a more concise way of using Select Case here?

I'm testing an input to see if it consists of Japanese characters, which fall within a certain unicode block. I could do it with If, but I like the neater syntax for Select Case. Said that, I'm not quite sure how to write a "Case" that excludes numbers falling between two values.

This works, but could possibly be written more concisely:

For Each c As Char In jpstring
    Select Case AscW(c)
        Case 12352 To 12543, 12784 To 12799

        Case Else
            Return False
    End Select
Next

I tried doing something like:

Case Not 12352 To 12543, 12784 To 12799

But that doesn't work, and nor does wrapping it in brackets like below:

Case Not (12352 To 12543, 12784 To 12799)

Is there a way to write a Case so that it specifically excludes multiple ranges of numbers?

Upvotes: 1

Views: 65

Answers (2)

Caius Jard
Caius Jard

Reputation: 74605

How about some LINQ?

Dim j() as Char = inputText.Select(Function(c) Ascw(c)).Where(Function(i) (i > 12351 AndAlso i < 12544) OrElse (i > 12783 AndAlso i < 12800))

Making an extension method might also be a nice way to tidy things up:

Module CharExtensions

    <Extension()> 
    Public Sub IsJapanese(c As char)
        Dim i = AscW(c)
        Return (i > 12351 AndAlso i < 12544) OrElse (i > 12783 AndAlso i < 12800
    End Sub
End Module



   Dim j() as Char = inputText.Where(Function(c) c.IsJapanese)

Upvotes: 0

Zev Spitz
Zev Spitz

Reputation: 15327

AFAIK there is no way to have a Case match an excluded range. However, you could use > and <:

For Each c As Char In jpstring
    Select Case AscW(c)
        Case < 12352, 12544 To 12783, > 12799
            Return False
        Case Else

    End Select
Next

Of course, if you only want to return True or False, it may be more concise to simply return the result of the comparison:

For Each c As Char In jpstring
    Dim asc = AscW(c)
    Return asc < 12352 OrElse (asc >= 12544 AndAlso asc <= 12783) OrElse asc > 12799
Next

Upvotes: 2

Related Questions