如何按列值过滤DataTable? [英] How I can filter my DataTable by Column Value?
本文介绍了如何按列值过滤DataTable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 DataTable
有疑问。我从数据库中检索 DataTable
,这些列之一包含1或0。现在我只想检索其中1值为1的行。列。
I have a question about DataTable
. I retrieve a DataTable
from 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.
列的名称为 ACTIVATE
。
这是我的 DataTable
:
DataTable table = new DataTable(TABLE);
//How can I filter here so ACTIVATE == 1?
adapter.Fill(table);
connection.Open();
selectcommand.ExecuteReader();
return table;
推荐答案
通过SQL(首选)
SELECT * FROM dbo.Table WHERE ACTIVATE = 1
通过 Linq-To-Datatable
(在内存中):
DataTable tblFiltered = table.AsEnumerable()
.Where(r => r.Field<int>("ACTIVATE") == 1)
.CopyToDataTable();
如果您仍然使用.NET 2,则可以使用 DataTable.Select
:
If you're still on .NET 2, you can use DataTable.Select
:
DataRow[] filteredRows = table.Select("ACTIVATE = 1");
除此之外,您不需要 selectcommand.ExecuteReader()
填充表格。
Apart from that, you don't need selectcommand.ExecuteReader()
to fill the table.
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 );
}
这篇关于如何按列值过滤DataTable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文