How I can filter my DataTable by Column Value?

戏子无情 提交于 2019-12-07 03:39:54

问题


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.

The name of the column is ACTIVATE.

Here is my DataTable:

DataTable table = new DataTable(TABLE);

//How can I filter here so ACTIVATE == 1?

adapter.Fill(table);

connection.Open();

selectcommand.ExecuteReader();

return table;

回答1:


Via SQL (preferred)

SELECT * FROM dbo.Table WHERE ACTIVATE = 1

Via Linq-To-Datatable (in memory):

DataTable tblFiltered = table.AsEnumerable()
                             .Where(r => r.Field<int>("ACTIVATE") == 1)
                             .CopyToDataTable();

If you're still on .NET 2, you can use DataTable.Select:

DataRow[] filteredRows = table.Select("ACTIVATE = 1");

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



回答2:


You simply use DataTable.Select like this:

 foundRows = table.Select("ACTIVATE = '1'");

It returns an array of DataRow objects.




回答3:


DataTable results = table.Select("ACTIVATE = 1").CopyToDataTable();

That should achieve what you want, basically you can query data tables much like SQL.




回答4:


return table;
DataTable results = table.Select("ACTIVATE = 1").CopyToDataTable();


来源:https://stackoverflow.com/questions/13701160/how-i-can-filter-my-datatable-by-column-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!