【问题标题】:vb.net: How to assign values to a list of variables dynamicallyvb.net:如何动态地为变量列表赋值
【发布时间】:2016-03-31 18:16:46
【问题描述】:

我有一个从数据源填充的 gridview,如下所示:

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

从该表中,我检查每个月的周数并计算它们,以便稍后获得平均值,这是我的代码。

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

这是Calcular() 函数:

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

我想做的是避免整个 Calcular() 函数,并“动态地”执行它。

换句话说,我想得到这样的东西:

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

intMonth 决定 Sum 将存储在哪个 WeekVariable 中。
根据我的理解,我尝试使用 List(Of T) 方法失败了,因为这会创建一个具有静态值的变量列表。

提前致谢

【问题讨论】:

  • 你可以使用字典colMonths(intMonth) +=1 如果你有一个数据源,你应该使用它而不是控件。您可能会写一个 linq 查询并一次获得所有 12(?) 个结果。看起来你应该打开 Option Strict
  • 您最好使用数组。然后只需使用Weeks(intMonth) = Weeks(intMonth) + 1。附带说明一下,您可以删除此行:intDate = GridView.Rows(X).Cells(0).Text。它的值没有被使用,你正在下一行重新分配它。
  • @Icemanind 是的,是的,那一行是正确的,只是编辑了代码,是一个拼写错误的行。关于Weeks(intMonth) = Weeks(intMonth) + 1,它抛出了这个错误:索引超出范围。必须是非负数且小于集合的大小。
  • @abichango - 你声明了吗? :Dim Weeks(12) As Integer
  • @Plutonix 你能解释一下字典方法吗,我在我的问题之前确实找过它,但不太明白。关于 Option Strict 这是一个我几乎没有参与的庞大项目,如果我打开它,我不知道其他表单会出现什么问题:/

标签: .net vb.net collections


【解决方案1】:

根据我们在您的 cmets 中的对话,您应该能够简单地执行此操作:

Dim Weeks(12) As Integer

然后将您对 Calcular() 的调用替换为:

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

这将创建一个数组来保存一年中(12 个月)中每个月的总和。

【讨论】:

    【解决方案2】:

    给定一个 DataTable dt 作为 DataSource 并且单元格/项目 1(不是 0)具有格式化的日期,您可以创建一个 Dictionary(of Int32, Int32) 来保存每个月的计数。迭代表应该比在控件周围戳更快;此外,DataTable 是数据所在的位置。

    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
    

    一些槽位将为零,因为代码提前将它们全部添加。 List(Of Int32) 也可以使用 MonthList(n) 来表示 N-1 月份。也可以一行查询表、分组、计数:

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

    在这种情况下,结果是一个包含月份和计数的简洁列表(我的日期列表是:{#1/11/2016#, #1/23/2016#, #1/16/2016#, #2/11/2016#, #4/15/2016#}):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多