2013-05-16 47 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

相关问题