对数据表值的数学函数,使用数组可能吗?

时间:2013-10-12 17:22:24

标签: c# sql winforms

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

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

现在,我可以从那些例如制作数学方程式。 (column1 + colum2) - (column3 * column4)

这可能,可能使用数组???

谢谢你们

2 个答案:

答案 0 :(得分: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

UPDATE:

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");

答案 1 :(得分:0)

如果我想做:Result =(1 / Priority)* JobComplex

示例:如果工程师有以下职位:

Enginner Jhon:优先级= 2,JobComplex = 2;然后(1/2)* 2 = 1

Enginner Mark:优先级= 1,JobComplex = 3;然后(1/1)* 3 = 3

然后Enginner Mark更加忙碌。

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);
}

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