C# 如何按列值过滤我的数据表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13701160/
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
How I can filter my DataTable by Column Value?
提问by Tarasov
I have a question about DataTable. I retrieve a DataTablefrom the database, and one of these columns contains either a 1 or a 0. Now I want to retrieve only the rows with a 1 value of 1 in that column.
我有一个关于DataTable. 我DataTable从数据库中检索 a ,其中一列包含 1 或 0。现在我只想检索该列中 1 值为 1 的行。
The name of the column is ACTIVATE.
列的名称是ACTIVATE。
Here is my DataTable:
这是我的DataTable:
DataTable table = new DataTable(TABLE);
//How can I filter here so ACTIVATE == 1?
adapter.Fill(table);
connection.Open();
selectcommand.ExecuteReader();
return table;
采纳答案by Tim Schmelter
Via SQL (preferred)
通过 SQL(首选)
SELECT * FROM dbo.Table WHERE ACTIVATE = 1
Via Linq-To-Datatable(in memory):
通过Linq-To-Datatable(在内存中):
DataTable tblFiltered = table.AsEnumerable()
.Where(r => r.Field<int>("ACTIVATE") == 1)
.CopyToDataTable();
If you're still on .NET 2, you can use DataTable.Select:
如果您仍在使用 .NET 2,则可以使用DataTable.Select:
DataRow[] filteredRows = table.Select("ACTIVATE = 1");
Apart from that, you don't need selectcommand.ExecuteReader()to fill the table.
除此之外,您不需要selectcommand.ExecuteReader()填写表格。
DataTable table = new Datatable();
using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand("SELECT * FROM dbo.Table WHERE ACTIVATE = 1", con))
using(var da = new SqlDataAdapter(cmd))
{
da.Fill( table );
}
回答by gideon
You simply use DataTable.Selectlike this:
您只需像这样使用DataTable.Select:
foundRows = table.Select("ACTIVATE = '1'");
It returns an array of DataRow objects.
它返回一个 DataRow 对象数组。
回答by Ryan McDonough
DataTable results = table.Select("ACTIVATE = 1").CopyToDataTable();
That should achieve what you want, basically you can query data tables much like SQL.
这应该可以实现您想要的,基本上您可以像 SQL 一样查询数据表。
回答by Soner G?nül
return table;
DataTable results = table.Select("ACTIVATE = 1").CopyToDataTable();

