C#:使用 PrimaryKey 从 DataTable 中检索值

标签 c# ado.net datatable primary-key

我的 C# 代码有问题。我已经设置了几个数据表,每个数据表都分配了一个主键。我想要做的是从单个列中检索单个行。

假设我有这段代码:

DataColumn Pcolumn = new DataColumn();
DataColumn[] key = new DataColumn[1];

Pcolumn.DataType = System.Type.GetType("System.Double");

Pcolumn.ColumnName = "length";
key[0] = Pcolumn;


table6F.Columns.Add(Pcolumn);
table6F.Columns.Add("Area", typeof(double));
table6F.Columns.Add("load", typeof(double));
table6F.Columns.Add("weigth", typeof(double));

table6F.PrimaryKey = key;
table.Rows.Add(6.0, 14.0, 17.8 , 11.0 );
table.Rows.Add(7.0, 16.2 , 20.7 , 16.0 );

我想检索第二行 (20.7) 的“负载”,我想在表中搜索主键列 7.0。我模拟测试这样做,只是为了测试:

Object oV;
double load;

//Get an Table object given the specific row number, this dummy i always set to 0.
// Given Column
oV = table.Rows[0]["load"];
load = Convert.ToDouble(oV.ToString());

有没有类似的方式使用主键提取?

最佳答案

您可以从 DataTable 中检索一行基于其主键使用 DataRowCollection.Find方法。在您的情况下,它将是:

DataRow matchingRow = table.Rows.Find(7.0D);
double value = (double)matchingRow["load"];

关于C#:使用 PrimaryKey 从 DataTable 中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9274732/

相关文章:

c# - List 的 Add 和 Append 方法之间的区别?

c# - 如何将java代码与c#代码连接起来?

c# - 在代码隐藏中动态引用控件(表)

c# - DataTable.Load() 时应用程序中断,问题在哪里?

c# - 参数化 SQL 查询

javascript - DataTables 函数 - table.row.add ,不使用表内的按钮(javascript)

c# - 如何在 Dapper 中使用 Char 和 VarBinary?

c# - 2个线程同时进入一个锁定的代码块

c# - 如何在 WinForms 中绑定(bind)多对多关系?

SqlDb类型和地理