1

我可以从数据表中获取值(所有大整数)并将数学函数应用于它们吗?例如,假设(所有记录 1):

Column 1 = 10;
Column 2 = 20;
Column 3 = 5;
Column 4 = 60;

现在,我可以从这些例如做一个数学方程式吗?(column1 + column2)-(column3 * column4)

这可能吗,也许使用数组???

多谢你们

4

2 回答 2

2

您可以使用此技巧来获取所有行的结果:

//Suppose you create your DataTable like this:
var dt = new DataTable();
dt.Columns.Add("Col1",typeof(int));
dt.Columns.Add("Col2",typeof(int));
dt.Columns.Add("Col3",typeof(int));
dt.Columns.Add("Col4",typeof(int));
//Add some rows to test
dt.Rows.Add(1, 2, 3, 4);
dt.Rows.Add(2, 2, 2, 2);
dt.Rows.Add(4, 2, 3, 3);

//Use this method to extract the result, remember that it's just demo
private List<int> GetResultColumn(DataTable dt){
  dt.Columns.Add("Result",typeof(int));
  dt.Columns["Result"].Expression = "(Col1+Col2)-(Col3*Col4)";
  List<int> result = dt.AsEnumerable().Select(row => row.Field<int>("Result")).ToList();
  dt.Columns.Remove("Result");
  return result;
}
//Use it
var result = GetResultColumn(dt);
//output  {0, -9, 0, -3}

您始终可以遍历行并以更标准的方式执行此操作,如下所示:

var result = dt.AsEnumerable()
               .Select(row=> row.Field<int>("Col1")+row.Field<int>("Col2") 
                            -row.Field<int>("Col3")*row.Field<int>("Col4"))
               .ToList();//Remove ToList() if you want

更新:

var newestRow = dt.AsEnumerable().Max(row=>row.Field<int>("ID"));
var result = newestRow.Field<int>("Col1") + newestRow.Field<int>("Col2") 
             -newestRow.Field<int>("Col3")* newestRow.Field<int>("Col4");
于 2013-10-12T17:33:02.453 回答
0

如果我想做:结果=(1 /优先级)* JobComplex

例如:如果工程师有以下工作:

工程师 Jhon:优先级 = 2,JobComplex = 2;那么 (1/2) * 2 = 1

工程师标记:优先级 = 1,JobComplex = 3;那么 (1/1) * 3 = 3

然后工程师马克更忙。

List<DataRow> theRows = new List<DataRow>();
decimal relativeBusy = 0;

foreach (DataRow row in EnginnerTable.Rows)
{    
 //1.- Get list of rows that match an "ID_Enginner"
 theRows = JobsTable.Select("ID_EnginnerAsigned=" + row["ID_Enginner"]).ToList();
 relativeBusy = 0;

 //2.- Foreach in "theRows" list, and make the math: Result = (1 / Priority) * JobComplex
 //** Priority and JobComplex are Columns...
 foreach (DataRow row2 in theRows)
 { 
   relativeBusy = relativeBusy + ((1 / Convert.ToDecimal(row2["Priority"])) * Convert.ToDecimal(row2["JobComplex"]));
 }

 //3.- Save the result on a List<decimal> to add to "Relative" Column of a Table after...
 jobsrelativeBusy.Add(relativeBusy);
}

你可以让数学更复杂......

于 2014-03-31T16:46:06.090 回答