我想在数据表中添加值 [英] I Want to add values inside the datatable

查看:84
本文介绍了我想在数据表中添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我的价值观是
数据表dt;

 dt.row [ 0 ] [ 0 ] =  10 ,
dt.row [ 0 ] [ 1 ] =  20 ,
dt.row [ 0 ] [ 2 ] =  30 ,
dt.row [ 0 ] [ 3 ] =  40 ,
dt.row [ 0 ] [ 4 ] =  50 ,
dt.row [ 0 ] [ 5 ] =  60 // ,很快....  


现在我想将第一列的不同行的数据表中的所有值相加...

10 + 20 + 30 + ........


谁能告诉我该怎么做...

解决方案

方法繁多!
最简单的理解是:

 DataTable dt;
...
DataRow dr = dt.Rows [ 0 ];
 int  sum =  0 ;
 foreach (对象 o  in 中的Dr.ItemArray )
    {
    如果(o   int )
        {
        sum + =( int )o;
        }
    }





  for ( int  i =  0 ;我<  dt.Rows.Count; i ++)
                {
                   如果(dt.Rows [i] [ 1 ].ToString()!= 字符串 yy = dt.Rows [i] [ 1 ].ToString();
                       计数= yy +计数;
                  }

                } 

但row [0] [1]的值未与row [1] [1]的值相加."
试试:

  int  count =  0 ;
 for ( int  i =  0 ; i <  dt.Rows.Count; i ++)
    {
    如果(dt.Rows [i] [ 1 ].ToString()!=  int )dt.Rows [i] [ 1 ];
       }
    }


它非常简单,您只需要放置2个FOR循环,1个用于行和其他用于列.
如果只想添加第一列的行,则只能使用1个FOR循环.


  var  sum = dt.AsEnumerable().Sum(x => x.Field< int>(" )); 


hi
i''m having values like
datatable dt;

dt.row[0][0]=10,
dt.row[0][1]=20,
dt.row[0][2]=30,
dt.row[0][3]=40,
dt.row[0][4]=50,
dt.row[0][5]=60, //and soon....


now i want to add all the values in the datatable of different rows of first column...

i.e 10+20+30+........


can any one tell me how to do this thing...

解决方案

There are loads of ways!
The simplest to understand is:

DataTable dt;
...
DataRow dr = dt.Rows[0];
int sum = 0;
foreach (object o in dr.ItemArray)
    {
    if (o is int)
        {
        sum += (int)o;
        }
    }





for (int i = 0; i < dt.Rows.Count; i++)
                {
                   if (dt.Rows[i][1].ToString() != null)
                   {
                       string yy = dt.Rows[i][1].ToString();
                       count = yy + count;
                  }

                }

"but row[0][1] value not adding with the row[1][1] value.."
Try:

int count = 0;
for (int i = 0; i < dt.Rows.Count; i++)
    {
    if (dt.Rows[i][1].ToString() != null)
       {
       count += (int) dt.Rows[i][1];
       }
    }


Its very very simple, you just need to put 2 FOR loops, 1 for rows and other for columns.
If you want addition of rows of only first column, you can use only 1 FOR loop.


var sum = dt.AsEnumerable().Sum(x=>x.Field<int>("SomeProperty"));


这篇关于我想在数据表中添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆