[LINQ] 查詢DataRow欄位(LINQ to DataSet)

  • 23617
  • 0
  • LINQ
  • 2010-09-23

[LINQ] 查詢DataRow欄位(LINQ to DataSet)

除了用DataView來查詢DataRow之外,我們還可以用LINQ查詢DataRow,這真是一個簡單的方法,不禁越來越喜歡LINQ。

首先我們建立一個DataTable

DataTable table = new DataTable("newTable");
string[] field = new string[] { "ID", "Name", "Phone" };
foreach (var item in field)
{
    DataColumn column = new DataColumn();
    column.ColumnName = item;
    column.Caption = item;
    column.AllowDBNull = true;
    table.Columns.Add(column);
}
DataRow row = table.NewRow();
row["ID"] = "1";
row["Name"] = "王大明";
row["Phone"] = "0780";
table.Rows.Add(row);
row = table.NewRow();
row["ID"] = "2";
row["Name"] = "余小章";
row["Phone"] = "0781";
table.Rows.Add(row);
this._Table = table;
dataGridView1.DataSource = table;
 

再來建立LINQ查詢方法

public void QueryLINQ(){
    //查尋DataTable的欄位
    var query = from contact in this._Table.AsEnumerable()
                where contact.Field<string>("Name").IndexOf("余") > -1//過濾條件
                select contact;
    //將查詢結果轉成DataTable
    DataTable table = query.CopyToDataTable();
    dataGridView2.DataSource = table;
}

 

順道把DataView的查詢方法列出來

public void QueryView(){
    DataView view = new DataView(this._Table);
    view.RowFilter = "Name='" + "余小章" + "'";
    DataTable table = view.ToTable();
    dataGridView3.DataSource = table;
}
 

執行結果是一樣的

image

接下來為我們寫的方法建立單元測試,觀察這兩個方法的執行時間吧~

image

 

Duration即是執行時間,用DataView查詢有明顯的勝出,LINQ固然方便好用,但效能怎麼差那麼多~

image 

 

範例下載

CS_LINQtoDataSet.zip

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo