2013-05-16 86 views
1

我正在開發一個例程來計算正確的期貨合約前月 如果我有一個表示月份數的整數數組,例如「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 

但我的。如果波浪得到一個VS2012下nextmonth THEN ELSE的

回答

3

「的IEnumerable的可能多個枚舉」警告我認爲這是你想要什麼:

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 
+0

如何從每個循環創建這個Dim個月= {1,4,7,10,12}?我從XML文件中獲取整數數組,並將它們作爲字符串獲取,並將它們轉換爲一個整數數組,如下所示:Dim contractonths()integer = GetMonthNumberfromShortMonthName(subnode.Name)(「subnode.Name是短月名稱) – dinotom

+0

然後我會使用'List(Of Int312)'而不是數組。如果你堅持要一個數組,你可以在末尾使用'list.ToArray()'。 –

+0

請看我的帖子編輯請 – dinotom

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

相關問題