DataTable篩選合格DataRow

來源:互聯網
上載者:User

 

DataTable篩選合格DataRow

 

DataTable中篩選row,在.net framework3.5和4.0中因為有linq,所以會有比較容易,相對的,在framework2.0中,稍顯笨拙了點,不過同樣很好用。就是使用DataTable.Select()方法,具體定義如下:

public DataRow[] Select (string filterExpression,string sort)

ex:DataRow[] rows=dt.Select("name like '%jake%'","age desc");

篩選出行集合之後,就是要將行集合匯入到一個新的DataTable中去。

步驟如下:

1.DataTable dtNew=dt.Clone();新的dtNew和dt具有同樣的架構和約束

2.此處需要注意,不能用foreach或for迴圈的方式將新的rows集合添加到dtNew中,會提示報錯,說行是屬於其他的DataTable,使用另外一個方法可以實現。

for(int i=0;i<rows.Length;i++)

{

dtNew.ImportRow(rows[i]);

}

查詢MSDN,會發現該方法的定義:將 DataRow 複製到 DataTable 中,保留任何屬性設定以及初始值和當前值。

備忘:調用 NewRow 時,將使用現有的表架構向表中添加一行,並為該行填充預設值,同時將 DataRowState 設定為 Added。 調用 ImportRow 將保留現有的 DataRowState 以及該行中的其他值。

 

 

 

--------------------------------------------------MSDN-----------------------------------------------

private void GetRowsByFilter()
{
    DataTable table = DataSet1.Tables["Orders"];
    // Presuming the DataTable has a column named Date.
    string expression;
    expression = "Date > #1/1/00#";
    DataRow[] foundRows;

    // Use the Select method to find all rows matching the filter.
    foundRows = table.Select(expression);

    // Print column 0 of each returned row.
    for(int i = 0; i < foundRows.Length; i ++)
    {
        Console.WriteLine(foundRows[i][0]);
    }
}

   Select()()()  擷取所有 DataRow 對象的數組。
    Select(String)  按照主鍵順序(如果沒有主鍵,則按照添加順序)擷取與篩選條件相匹配的所有 DataRow 對象的數組。
    Select(String, String)  擷取按照指定的排序次序且與篩選條件相匹配的所有 DataRow 對象的數組。
    Select(String, String, DataViewRowState)  擷取與排序次序中的篩選器以及指定的狀態相匹配的所有 DataRow 對象的數組。

    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.