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

发布于 2025-01-05 11:26:43 字数 870 浏览 3 评论 0原文

我的 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());

是否有类似的方法使用主键提取?

I have a issue with my code in C#. I have set up a couple of DataTables with a primary key assigned to each of them. what I want to do is to retrieve a single row from a single column.

Lets say I have this code:

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

And I want to retrieve the the "load" for the second row (20.7), I would like to search for 7.0, primary key column, in the Table. I dummy tested to do like this, just to test:

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

Is there a similar way to extract using the Primary key?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌面超妹 2025-01-12 11:26:43

您可以根据 DataTable 检索行使用 DataRowCollection.Find 方法的主键。在你的情况下,它将是:

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

You can retrieve a row from a DataTable based on its primary key using the DataRowCollection.Find method. In your case it would be:

DataRow matchingRow = table.Rows.Find(7.0D);
double value = (double)matchingRow["load"];
暮光沉寂 2025-01-12 11:26:43

您可以使用 Find 方法使用主键查找行

DataRow row = dataTable.Rows.Find("your key");
if(null != row)
{
    string value = row["ColumnName"];
}

You can use Find method to find a row using primary Key

DataRow row = dataTable.Rows.Find("your key");
if(null != row)
{
    string value = row["ColumnName"];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文