将值更改为数组中的下一个值

时间:2013-05-16 08:50:35

标签: vb.net

我正在开发一个例程来计算正确的期货合约前月 如果我有一个表示月份数的整数数组,即“1,4,7,10,12” 我有一个2的变量整数。

如果变量本身不在数组中,如何针对数组测试变量并将变量更改为数组中可用的下一个最高值?即在这种情况下,变量的值2将变为4。

我尝试了各种各样的方法但现在卡住了

If datenum >= (targetdayofmonth + adjdays) Then
        currentmonth = currentmonth + 1
        Dim currmonthname As String = MonthName(currentmonth, True)
        For x As Integer = 0 To contractmonths.Count - 1
            If GetMonthNumberfromShortMonthName(contractmonths(x)) = currentmonth Then
                currmonthname = currmonthname
            Else

            End If
        Next
    Else
        Dim currmonthname As String = MonthName(currentmonth, True)
    End If

基于Tim的评论,我已将代码更新为;

 Dim contractmonthNos As New List(Of Int32)
    For Each childnode As XmlNode In From childnode1 As XmlNode In root Where childnode1.SelectSingleNode("futures/symbol/Code").InnerText = commodcode
        'get the available contract months for this contract
        Dim contractmonthnodes As XmlNode = childnode.SelectSingleNode("ContractMonths")
        contractmonthNos.AddRange(From subnode As XmlNode In contractmonthnodes Select GetMonthNumberfromShortMonthName(subnode.Name))
    Next
If datenum >= (targetdayofmonth + adjdays) Then
        currentmonth = currentmonth + 1
        Dim currmonthname As String = MonthName(currentmonth, True)
    Else
        Dim nextmonth = From month As Integer In contractmonthNos Where month >   currentmonth
        If nextmonth.Any() Then
            currentmonth = nextmonth.First()
        End If
        Dim currmonthname As String = MonthName(currentmonth, True)
    End If

但是我在下一个月的“If Then Else”警告“可能多次枚举IEnumerable”中获得VS2012波浪形

2 个答案:

答案 0 :(得分:3)

我认为这就是你想要的:

Dim intVar = 2
Dim months = { 1,4,7,10,12 }
Dim higherMonths = months.Where(Function(month) month > intVar).ToArray()
If higherMonths.Any() Then
    intVar = higherMonths.First()
End If

如果您不想要数组中的下一个可用月份,但最近必须排序:

Dim higherMonths = months.Where(Function(m) m> intVar).
                          OrderBy(Function(m) m).
                          ToArray()
If higherMonths.Any() Then
    intVar = higherMonths.First()
End If

答案 1 :(得分:0)

这样的东西
Module Module1

    Sub Main()
        ' N.B. this needs to the array to be sorted.
        Dim a() As Integer = {1, 4, 7, 10, 12}
        Dim toFind As Integer = 2
        Dim foundAt As Integer = -1
        For i = 0 To a.Length() - 1
            If a(i) >= toFind Then
                foundAt = i
                Exit For
            End If
        Next

        If foundAt >= 0 Then
            Console.WriteLine(String.Format("Looked for {0}, found {1}.", toFind, a(foundAt)))
        Else
            Console.WriteLine(String.Format("Did not find {0} or higher.", toFind))
        End If

        Console.ReadLine()

    End Sub

End Module

或者您可能希望使用Array.BinarySearch Method