vb.net 循环遍历数据表 vb

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16324167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:27:25  来源:igfitidea点击:

looping through a data table vb

vb.netvisual-studio-2010datatable

提问by iDev

I'm trying to loop through a data table that has multiple values for my constraint. How can I keep the first value and add together all the other values that match my constraint.

我正在尝试遍历具有多个约束值的数据表。如何保留第一个值并将与我的约束匹配的所有其他值加在一起。

For i = 0 To ds.Tables(0).Rows.Count - 1

            If ds.Tables(0).Rows(i).Item("TEND_POS_ID") = 8 Then

              'This only returns the last value  
              'Value 1 = 2
              'Value 2 = 7.5
              'should = 9.5 but it is showing 7.5                  

             tmpCoupon = ds.Tables(0).Rows(i).Item("TENDER_AMT")
            End If
        Next
        txtCoupon.Text = tmpCoupon

采纳答案by Steve

If I understand your question correctly, you need to add the values of TENDER_AMTwhere the value in TEND_POS_IDis 8. If this is the case you could use the Selectmethod of the DataTable

如果我正确理解您的问题,您需要添加TENDER_AMT其中值为TEND_POS_ID8的值。如果是这种情况,您可以使用DataTable的Select方法

 Dim rows = ds.Tables(0).Select("TEND_POS_ID = 8")
 for each r in rows
    tmpCoupon += Convert.ToDecimal(r("TENDER_AMD"))
 Next

However, rembember that this kind of work (SUM a column grouping by another column) is usually better resolved by the query that you submit to the database. Something like this:

但是,请记住,您提交到数据库的查询通常可以更好地解决此类工作(按另一列对列进行分组)。像这样的东西:

SELECT TEND_POS_ID, SUM(TENDER_AMD) FROM Table1 GROUP BY TEND_POS_ID