我想从for循环的条件中获取总数,假设对于第一行(I),代码将检查if条件,如果条件满足特定月份,则使用特定的for循环来获取列数(例如:如果行的月份为1,则将k As Integer = 4应用于dt.Columns.Count-1以获取计数,如果行的月份为2,则将k作为Integer = 4应用于dt .Columns.Count-2以获取计数等),然后是第二行(I),依此类推,如果条件k然后返回总计数,我该如何实现?
我尝试了下面的方法,但是下面的代码没有按照上面的描述工作,它仅返回第一个条件的计数,请指导我:
For I As Integer = 0 To dt.Rows.Count - 1
'If dt.Rows(I).Item("Month").ToString = "1" Or dt.Rows(I).Item("Month").ToString = "3" Or dt.Rows(I).Item("Month").ToString = "5" Or dt.Rows(I).Item("Month").ToString = "7" Or dt.Rows(I).Item("Month").ToString = "8" Or dt.Rows(I).Item("Month").ToString = "10" Or dt.Rows(I).Item("Month").ToString = "12" Then
For k As Integer = 4 To dt.Columns.Count - 1
If dt.Rows(I).Item(k).ToString() = "1" Then
count1 += 1
Else
count1 = 0
End If
If count1 > 13 Then
Dx = True
End If
Next k
'ElseIf dt.Rows(I).Item("Month").ToString() = "2" Or dt.Rows(I).Item("Month").ToString() = "4" Or dt.Rows(I).Item("Month").ToString() = "6" Or dt.Rows(I).Item("Month").ToString() = "9" Or dt.Rows(I).Item("Month").ToString() = "11" Then
'For k As Integer = 4 To dt.Columns.Count - 2
'If dt.Rows(I).Item(k).ToString() = "1" Then
' count1 += 1
'Else
' count1 = 0
'End If
' If total > 13 Then
' Dx = True
' End If
'Next k
'End If
Next I
DataTable(列代表日期,第11个月有30列,第12个月有31列)
----------------------------------------------------------------------------
Id | year | month | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | till 31
----------------------------------------------------------------------------
kek | 2019 | 10 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
kek | 2019 | 11 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 |
kek | 2019 | 12 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 |
预期输出:
如果从11/11到12/12的连续计数大于13,则dx返回true。
答案 0 :(得分:0)
在当前代码中,您将每个count1
中的Else
重置为零。
此代码:
total += count1
If total > 13 Then
Dx = True
End If
...看起来应该在循环之外。
在我看来您需要这个:
For I As Integer = 0 To dt.Rows.Count - 1
Dim offset = 2
If {"1", "3", "5", "7", "8", "10", "12"}.Contains(dt.Rows(I).Item("Month").ToString())
offset = 1
End If
For k As Integer = 4 To dt.Columns.Count - offset
If dt.Rows(I).Item(k).ToString() = "1" Then
count1 += 1
End If
Next
Next
If count1 > 13 Then
Dx = True
End If
如果您想变得更高级,请尝试LINQ:
Dim query = _
From dr In dt.Rows.OfType(Of DataRow)()
Let offset = If({"1", "3", "5", "7", "8", "10", "12"}.Contains(dr.Item("Month").ToString()), 0, 1)
From k In Enumerable.Range(4, dt.Columns.Count - offset)
Where dr.Item(k).ToString() = "1"
Select 1
Dim total = query.Sum()
If total > 13 Then
Dx = True
End If