簡體   English   中英

如何使用 Linq 過濾數據表到數據表?

[英]How I can filter a dataTable with Linq to datatable?

嗨,我如何使用 linq to datatable 過濾數據表? 我有一個 DropDownList,在那里我可以選擇 Modul Column 的值。 現在我想用這個模塊列過濾數據表。

這是我的數據表結構:

User | Host | TimeDiff | License | Telefon | Modul 

這里的代碼:

protected void drp_Modules_SelectedIndexChanged(object sender, EventArgs e)
{
    string value = drp_Modules.SelectedValue;

    DataTable tb = (DataTable)Session["dt_Users"];

    tb = from item in tb //?????

    LoadUsertable(tb);
}

您最好使用DataTable.Select方法,但如果您必須使用 LINQ,那么您可以嘗試:

DataTable selectedTable = tb.AsEnumerable()
                            .Where(r => r.Field<string>("Modul") == value)
                            .CopyToDataTable();

這將根據過濾的值創建一個新的DataTable

如果您使用DataTable.Select

string expression = "Modul =" + value;
DataRow[] selectedRows = tb.Select(expression);

您可以在轉換之前使用條件來檢查行是否存在。 Any() 工作需要 System.Linq 命名空間

var rows = values.AsEnumerable().Where
            (row => row.Field<string>("Status") == action);//get the rows where the status is equal to action

if(rows.Any())
{
    DataTable dt = rows.CopyToDataTable<DataRow>();//Copying the rows into the DataTable as DataRow
}

基於過濾項目列表檢索數據表。 (即,如果數據表中存在任何列表項,則將收到匹配的結果。

 List<string>item=new List<string>(){"TG1","TG2"};     
 DataTable tbsplit = (from a in tbl.AsEnumerable()
              where item.Any(x => a.Field<string>("CSubset").ToUpper().Contains(x.ToUpper()))
              select a).CopyToDataTable();//By Executing this, the Filter DataTable is obtained

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM