简体   繁体   中英

vb.net: How to assign values to a list of variables dynamically

I have a gridview which is populated from a datasource, as such:

   Date              Hours
 January/2016        26.31
 January/2016        25.65
 February/2016       12.3
   ....          ...     ....

From that table I check for the weeks every month had and count them, so I can get an average later on, this is my code.

For intMonth = 1 To 12
    For X = 0 To GridView.Rows.Count - 1

        intDate = Convert.ToDateTime(gvTiempos.Rows(X).Cells(0).Text)

        If DatePart("m", intDate) = intMonth Then
            Calcular()            
        End If

      Next
Next

This is the Calcular() function:

Public Function Calcular()
 Select Case intMonth
   Case 1: JanWeeks+=1
   Case 2: FebWeeks+=1
    ...
   Case 12: DecWeeks+=1

What I would like to do is to avoid the whole Calcular() function, and do it "dynamically".

In other words, I would like to get something like this:

 Weeks(intMonth) = "Sum of Weeks for that month"

Where intMonth determinate in which WeekVariable the Sum will be storaged.
I have tried with the List(Of T) method unsuccessfully, because this creates a list of variables with a static value, according to my understanding.

Thanks in advance

Given a DataTable dt as the DataSource and cell/item 1 (not 0) has the formatted date, you can create a Dictionary(of Int32, Int32) to hold the count for each month. Iterating the table should be faster than poking around the control; besides, the DataTable is where the data is.

Dim col As New Dictionary(Of Int32, Int32)
' create 12 keys for 12 months
For n As Int32 = 1 To 12
    col.Add(n, 0)
Next

For Each row As DataRow In dt.Rows
    col(Convert.ToDateTime(row(1)).Month) += 1
Next

Some slots will be zero, because the code added them all ahead of time. A List(Of Int32) would also work using MonthList(n) to represent the month N-1. You can also just query the table, group and count in one line:

Dim monthCount = dt.AsEnumerable.GroupBy(Function(v) v.Field(Of DateTime)(1).Month,
                            Function(k, v) New With {.Month = k, .Count = v.Count()}).
                       ToArray()

In this case, the result is a succinct list with the month and count (my date list was: {#1/11/2016#, #1/23/2016#, #1/16/2016#, #2/11/2016#, #4/15/2016#} ):

在此处输入图片说明

As per our conversation in your comments, you should be able to simply do this:

Dim Weeks(12) As Integer

Then replace your call to Calcular() to this:

If DatePart("m", intDate) = intMonth Then
    Weeks(intMonth) = Weeks(intMonth) + 1
End If

This creates an array to hold the sum for each month in the year (12 months).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM