繁体   English   中英

如何查询C#DataTable?

[英]How to query C# DataTable?

我已经创建并返回了数据表,该表有10列。 现在,我想根据一些动态搜索参数从该表中进行过滤。 这个怎么做? 任何想法将是及时的帮助。

// This function will create and return the source table.
var DisplayTable = CreateQueryTable(); 

在这里,我想进行动态搜索,例如, If col1=MyName and Col2=MyCity

ResultGrid.DataSource = DisplayTable;
ResultGrid.DataBind();
Panel1.Controls.Add(ResultGrid);

您可以通过这种方式做到这一点,

1,创建像

var dv = dataTable.DefaultView;
dv.RowFilter =  "col1='MyName' and Col2='MyCity'"; // if MyName and MyCity are literal string.

要么

dv.RowFilter = "col1='"+MyName+"' and Col2 ='"+ MyCity +"'";// if MyName and MyCity are string variable.

2.使用DataTable Select方法,将返回DataRow数组

var rows = dataTable.Select("col1='MyName' and Col2='MyCity'"); //if string literal

要么

var rows = dataTable.Select("col1='"+MyName+"' and Col2='"+MyCity+"'"); // if string variable

3.由Linq

var filterdData = from row in dataTable.AsEnumerable()
                  where row.Field<string>("col1") == "MyName" 
                  && row.Field<string>("col2") == "MyCity"
                  select row;

您创建数据表的DataView并使用Filter //创建一个DataView DataView dv = new DataView(yourDataTable); dv.RowFilter =“ col1 ='MyName'和Col2 ='MyCity'”; //使用DataView绑定网格

您还可以在表格上使用选择方法

  DataRow[] foundRows;
  foundRows = yourDataTable.Select("col1='MyName' and Col2='MyCity'");

您也可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM