[英]How to query C# DataTable?
I have created and returned datatable, this table has 10 columns. 我已经创建并返回了数据表,该表有10列。 Now i want to filter from this table based on some dynamic search parameters.
现在,我想根据一些动态搜索参数从该表中进行过滤。 How to do this?
这个怎么做? any idea would be timely help.
任何想法将是及时的帮助。
// This function will create and return the source table.
var DisplayTable = CreateQueryTable();
Here I want to do dynamic search like If col1=MyName and Col2=MyCity
在这里,我想进行动态搜索,例如,
If col1=MyName and Col2=MyCity
ResultGrid.DataSource = DisplayTable;
ResultGrid.DataBind();
Panel1.Controls.Add(ResultGrid);
You can do this in these way, 您可以通过这种方式做到这一点,
1.Creating DataView Like 1,创建像
var dv = dataTable.DefaultView;
dv.RowFilter = "col1='MyName' and Col2='MyCity'"; // if MyName and MyCity are literal string.
or 要么
dv.RowFilter = "col1='"+MyName+"' and Col2 ='"+ MyCity +"'";// if MyName and MyCity are string variable.
2.With DataTable Select Method, It will return array of DataRow 2.使用DataTable Select方法,将返回DataRow数组
var rows = dataTable.Select("col1='MyName' and Col2='MyCity'"); //if string literal
or 要么
var rows = dataTable.Select("col1='"+MyName+"' and Col2='"+MyCity+"'"); // if string variable
3.By Linq 3.由Linq
var filterdData = from row in dataTable.AsEnumerable()
where row.Field<string>("col1") == "MyName"
&& row.Field<string>("col2") == "MyCity"
select row;
you create DataView of your datatable and use Filter // Create a DataView DataView dv = new DataView(yourDataTable); 您创建数据表的DataView并使用Filter //创建一个DataView DataView dv = new DataView(yourDataTable); dv.RowFilter = "col1='MyName' and Col2='MyCity'";
dv.RowFilter =“ col1 ='MyName'和Col2 ='MyCity'”; //Bind your grid with DataView
//使用DataView绑定网格
You can also use select method on your table 您还可以在表格上使用选择方法
DataRow[] foundRows;
foundRows = yourDataTable.Select("col1='MyName' and Col2='MyCity'");
You can also use Linq To DataTable 您也可以使用Linq To DataTable
var results = from myRow in yourDataTable.AsEnumerable()
where myRow.Field<string>("col1") == Myname &&
myRow.Field<string>("Col2") == MyCity
select myRow;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.