将列与外部值分开 [英] Divide column with external value

查看:84
本文介绍了将列与外部值分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据表有一个名为 TotalAmount 的列。要获得总计,我必须将该列中的所有值相加。这很简单:



My datatable has a column called TotalAmount. To get grand total I have to sum all the value in that column. That's easy:

var sum = dt.Compute("Sum(TotalAmount)","");





现在我需要创建另一个名为<$ c $的列c> PercentTotal 在数学上说 TotalAmount / sum



是否有一个数据表方法允许我更容易地表达它,而不是每次迭代行和计算该特定列的值。



Now I need to create another column called PercentTotal which is mathematically speaking TotalAmount/sum .

Is there a datatable method which allows me to express this more easily rather than iterate the rows and compute value for that specific column everytime.

推荐答案

是的,您可以通过在DataTable中添加一个已定义表达式的列来实现此目的。

喜欢这样......

Yes, you can do this by adding a column to your DataTable that has an expression defined.
Like so...
DataTable tbl = new DataTable("TestTable");

DataColumn c = new DataColumn("Col1", typeof(Int32));
tbl.Columns.Add(c);
c = new DataColumn("Col2", typeof(Int32));
tbl.Columns.Add(c);

// create expression data column and add to table
// the third parameter defines the expression.
c = new DataColumn("Col3", typeof(Decimal), "Col1 / Col2");
tbl.Columns.Add(c);

for (int i = 1; i <= 10; i++)
{
    DataRow r = tbl.NewRow();
    r["Col1"] = i;
    r["Col2"] = (i + 10);
    // don't set Col3 as the expression will automatically used to set the value
    tbl.Rows.Add(r);
}


如果 dt Data.DataTable object,你可以使用类似的东西:

If dt is a Data.DataTable object, you can use something like that:
//get System.Data.EnumerableRowCollection
var values = dt.AsEnumerable();
//get total from <code>myVal</code> field
int total = values.Sum(r=>r.Field<int32>("myVal"));
//do calculations using linq query
var PercSum = from v in values 
              select new
              {
                  Value = v.Field<int32>("myVal"),
                  SumOfValue = total,
                  Percentage = Convert.ToDecimal(v.Field<int32>("myVal")) / Convert.ToDecimal(total)
               };
//list values 
Console.WriteLine("Value | Sum | Percentage");
foreach (var p in PercSum )
{
    //
    Console.WriteLine("{0} | {1} | {2}", p.Value.ToString(), p.SumOfValue.ToString(),p.Percentage);
}


可以按如下方式完成:



It can be done as follows:

var sum = dt.Compute("Sum(TotalAmount)","");

var dc = new DataColumn ("PercentTotal", 
    typeof (double), 
    "TotalAmount / " + sum.ToString ());

dt.Columns.Add (dc);


这篇关于将列与外部值分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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