簡體   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