C# 数据表选择行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9544175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
datatable select rows
提问by Pramod
I am using a datatable created by program. In this datatable i want to insert values in some specified columns.
我正在使用由程序创建的数据表。在这个数据表中,我想在某些指定的列中插入值。
Initially I am inserting primary key values leaving remaining columns null, when I am querying datatable with recently inserted value in Primary column to update same row, I am facing error Missing operand after ID operator
最初我插入主键值,其余列为空,当我在主列中使用最近插入的值查询数据表以更新同一行时,我面临错误 Missing operand after ID operator
Can any one tell me the exact issue.
谁能告诉我确切的问题。
I am trying following code:
我正在尝试以下代码:
dt.Rows.Add(1);
int insertedValue = 1;
DataRow[] dr = dt.Select("ID = '" + insertedValue.toString() + "'");
And the table structure after entring primary value is as follows.
输入主值后的表结构如下。
ID Volumn1 Volumn2 volumn3
--------------------------------------
1
采纳答案by Tim Medora
You can do this more cleanly with LINQ and make this a strongly typed operation.
您可以使用 LINQ 更干净地执行此操作,并使其成为强类型操作。
Something like:
就像是:
dt.Rows.Add(1);
int insertedValue = 1;
var result =
dt.AsEnumerable().Where( dr => dr.Field<int>( "ID" ) == insertedValue );
Working example:
工作示例:
DataTable dt = new DataTable();
dt.Columns.Add( "ID", typeof( int ) );
dt.Rows.Add( 1 );
var result = dt.AsEnumerable().Where( dr => dr.Field<int>( "ID" ) == 1 );
回答by gideon
You do not need ' 'in your filter.
您不需要' '在您的过滤器中。
I think this should work:
我认为这应该有效:
DataRow[] dr = dt.Select("ID = " + insertedValue.toString());
回答by Sean
By the way, reference System.Data.DataSetExtensions
顺便说一下,参考 System.Data.DataSetExtensions
回答by Sunday Efeh
You can simply format the selection string as shown below:
您可以简单地格式化选择字符串,如下所示:
DataRow[] dr = dt.Select(string.Format("ID ='{0}' ", insertedValue));
Feel free to let me know if this works for you.. Thanks
如果这对你有用,请随时让我知道..谢谢
回答by Kyle Hymanson
If you are looking for a specific row and your datatable has a primary key you could use the Find method and target the primary key which would return just the row you want rather than an array:
如果您正在查找特定行并且您的数据表有一个主键,您可以使用 Find 方法并定位主键,该主键将只返回您想要的行而不是数组:
DataRow foundRow = dt.Rows.Find([INSERT SEARCH PARAMETER HERE]);
if(foundRow != null)
{
TO SET A STRING EQUAL TO A FOUND VALUE:
string str = foundRow["COLUMN NAME / INDEX];
OR IF YOU ARE INSERTING A VALUE YOU CAN USE IT LIKE THIS:
foundRow["COLUMN NAME / INDEX"] = NEW VALUE;
}
回答by Alparslan ?EN
select column of row
选择行列
dt.Rows[0].Field<string>("MyColumnName")

