Вопрос

The code below works, I can't help thinking there is a better way to do this though. Is anyone experienced with using functions in conjunction with Select Statements.
The code I would expect to work would be something along the lines...

Select Case File.EndsWith()
Case "example 1", Case "example2"

This code works:

Select Case File.EndsWith(File)
    Case tFile.EndsWith("FileA.doc")
        sbExisting.AppendLine(Report.sbStart.ToString)
        sbExisting.AppendLine(Report.sbHeaders.ToString)
        sbExisting.AppendLine(Report.sbItems.ToString)
        sbExisting.AppendLine(Report.sbSubreport.ToString)
        sbExisting.AppendLine(Report.sbEnd.ToString)
        sbExisting.AppendLine(Report.sbCol.ToString)
    Case tFile.EndsWith("FileB.doc")
        'Slave
        sbExisting.AppendLine(Report.sbStart.ToString)
        sbExisting.AppendLine(Report.sbItems.ToString)
        sbExisting.AppendLine(Report.sbHeaders.ToString)
        sbExisting.AppendLine(Report.sbCol.ToString)
        sbExisting.AppendLine(Report.sbEnd.ToString)
End Select
Это было полезно?

Решение

.EndsWith() returns true or false. That's all you have.

If you do want to use Select with that, then the idiomatic way is

Select Case True
    Case tFile.EndsWith("MSMaster.tmp")
        ...
    Case tFile.EndsWith("MSSlave.tmp")
        ...
End Select

Having multiple choices on the same line would be of not much difference:

Select Case True
    Case tFile.EndsWith("example 1"), tFile.EndsWith("example 2")
        ...
    Case tFile.EndsWith("example 3"), tFile.EndsWith("example 4")
        ...
End Select

If you already have a list of choices in an array/list/collection, you can also use

Dim choices1 = New String() {"example 1", "example 2"}
Dim choices2 = New String() {"example 3", "example 4"}

Select Case True
    Case choices1.Any(Function(s) tFile.EndsWith(s))
        ...
    Case choices2.Any(Function(s) tFile.EndsWith(s))
        ...
End Select

Or do the same inline if you prefer:

Select Case True
    Case (New String() {"example 1", "example 2"}).Any(Function(s) tFile.EndsWith(s))
        ...
    Case (New String() {"example 3", "example 4"}).Any(Function(s) tFile.EndsWith(s))
        ...
End Select

Другие советы

The only difference between the 2 cases is the appending of the sbSubreport item. That is the only item which needs a special check and can be done like the following

Dim master = tFile.EndsWith("MSMaster.tmp")
Dim slave = tFile.EndsWith("MSSlave.tmp")
If master OrElse slave Then
    sbExisting.AppendLine(Report.sbStart.ToString)
    sbExisting.AppendLine(Report.sbHeaders.ToString)
    sbExisting.AppendLine(Report.sbItems.ToString)
    If master Then
        sbExisting.AppendLine(Report.sbSubreport.ToString)
    End If
    sbExisting.AppendLine(Report.sbEnd.ToString)
    sbExisting.AppendLine(Report.sbCol.ToString)
End If
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top