C#-如何在DataTable中进行数学运算

时间:2019-02-21 01:40:52

标签: c# math datagridview datatable datarow

我有一个DataTable,我想先做一些数学运算,然后再将它们添加到DataGridView中。第一个,我想找到我的DataTable第三列的最大数目,第二个,我想用这个最大数目除以第三列的所有值。毕竟,我想替换新值而不是旧值。我的数据表看起来像这样;

        Column 1     Column 2     Column 3
     ---------------------------------------
          a             b          2000000
          q             r          250000
          s             t          185000
          m             w          400000
          o             p          750000

操作之后,我的DataTable应该看起来像这样;

        Column 1     Column 2     Column 3
     ---------------------------------------
          a             b          1
          q             r          0.125
          s             t          0.0925
          m             w          0.0002
          o             p          0.375

这是我的代码;

      connection.Open();
      //Some insignificant operations here.
      for (int q = 0; q < w.Length; q++)
      {
          for (int a = q + 1; a < w.Length; a++)
          {
              string query = ".....";
              SqlDataAdapter myAdapter = new SqlDataAdapter(query, connection);
              DataTable myTable = new DataTable();
              myAdapter.Fill(myTable);
              //I started here for finding maximum number in DataTable.
              int[] myColumn = dt.AsEnumerable().Select(x => x.Field<int>("Column3")).ToArray();
              int myMaximum = myColumn.Max();
              //I don't know what should I do after that.
              foreach (DataRow myRows in myTable.Rows)
              {
                  //Some significant operations again...
                  dgv1.Rows.Add(...);
              }
          }
      }
      connection.Close();

3 个答案:

答案 0 :(得分:0)

尝试一下:

var max = myTable.Rows.Cast<DataRow>().Max(r => r.Field<double>("Column 3"));

foreach (var row in myTable.Rows.Cast<DataRow>())
{
    row["Column 3"] = row.Field<double>("Column 3") / max;
}

可运行的测试代码:

var myTable = new DataTable();
myTable.Columns.Add("Column 3", typeof(double));
myTable.Rows.Add(20_00_000);
myTable.Rows.Add(250_000);
myTable.Rows.Add(185_000);
myTable.Rows.Add(400_000);
myTable.Rows.Add(750_000);

Console.WriteLine(String.Join(", ", myTable.Rows.Cast<DataRow>().Select(r => r.Field<double>("Column 3"))));    

var max = myTable.Rows.Cast<DataRow>().Max(r => r.Field<double>("Column 3"));

foreach (var row in myTable.Rows.Cast<DataRow>())
{
    row["Column 3"] = row.Field<double>("Column 3") / max;
}

Console.WriteLine(String.Join(", ", myTable.Rows.Cast<DataRow>().Select(r => r.Field<double>("Column 3"))));

这将输出:

2000000, 250000, 185000, 400000, 750000
1, 0.125, 0.0925, 0.2, 0.375

根据“列3”为int进行更新。

Console.WriteLine(String.Join(", ", myTable.Rows.Cast<DataRow>().Select(r => r.Field<int>("Column 3"))));

int max = myTable.Rows.Cast<DataRow>().Max(r => r.Field<int>("Column 3"));
double[] results = myTable.Rows.Cast<DataRow>().Select(r => (double)r.Field<int>("Column 3") / max).ToArray();

Console.WriteLine(String.Join(", ", results));

现在,在构建results时只需索引到DataGridView

答案 1 :(得分:0)

您是否考虑过在现有表中添加第4列?将列设为“表达式”列以按照您所描述的进行数学运算,然后隐藏第三列?

下面是一个例子……

DataTable GridTable;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  GridTable = GetDataTable();
  FillTable(GridTable);
  AddExpressionColumn(GridTable);
  dataGridView1.DataSource = GridTable;
  dataGridView1.Columns["Column3"].Visible = false;
}

private DataTable GetDataTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Column1", typeof(string));
  dt.Columns.Add("Column2", typeof(string));
  dt.Columns.Add("Column3", typeof(int));
  return dt;
}

private void FillTable(DataTable dt) {
  dt.Rows.Add("a", "b", 2000000);
  dt.Rows.Add("q", "r", 250000);
  dt.Rows.Add("s", "t", 185000);
  dt.Rows.Add("m", "w", 400000);
  dt.Rows.Add("o", "p", 750000);
}

private void AddExpressionColumn(DataTable dt) {
  DataColumn expCol = new DataColumn("Result", typeof(decimal));
  dt.Columns.Add(expCol);
  string expressionString = "Column3 / " + GetMaxValue(dt).ToString();
  expCol.Expression = expressionString;
}

private int GetMaxValue(DataTable dt) {
  int max = (int)dt.Compute("Max(Column3)", "");
  if (max == 0)
    return 1;
  return max;
}

答案 2 :(得分:0)

我建议您摆脱DataTable并使用普通的c#类。
DataTable是“繁重”的结构,它的作用远远超出您的需要,在大多数情况下,您不需要它。

创建用于表示您的数据的类

public class Item
{
    public string Column1 { get; set; }
    public string Column2 { get; set; }
    public int Column3 { get; set; }
}

加载数据

public List<Item> LoadData()
{
    var query = "SELECT Column1, Column2, Column3 FROM Table";
    using (var connection = new SqlConnection(connectionString))
    using (var command = connection.CreateCommand())
    {
        command.CommandType = CommandType.Text;
        command.CommandText = query;

        using (var reader = command.ExecuteReader())
        {
            var data = new List<Item>();
            while(reader.Read())
            {
                var item = new Item
                {
                    Column1 = reader.GetString(0),
                    Column1 = reader.GetString(1),
                    Column1 = reader.GetInt32(2)
                };
                data.Add(item);
            }

            return data;
        }
    }
}

创建将代表计算数据的类

public class CalculatedItem
{
    public string Column1 { get; }
    public string Column2 { get; }
    public decimal Calculated { get; }

    public CalculatedItem(Item item, decimal maxValue)
    {
        Column1 = item.Column1;
        Column2 = item.Column2;
        Calculated = (decimal)item.Column3 / maxValue
    }
} 

用法

var data = LoadData();
var maxValue = data.Select(item => item.Column3).Max();
var calculatedData = data.Select(item => new CalculatedItem(item, maxValue)).ToList();

// Bind data to the DataGridView
DataGridView1.DataSource = calculatedDate;