How I can filter a dataTable with Linq to datatable?

大憨熊 提交于 2019-11-27 12:59:41

问题


hi how i can filter a datatable with linq to datatable? I have a DropDownList and there I can select the value of the Modul Column. Now I want to filter the DataTable with this Modul Column.

here is my datatable structure:

User | Host | TimeDiff | License | Telefon | Modul 

Here the Code:

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);
}

回答1:


You are better of using DataTable.Select method, but if you have to use LINQ then you can try:

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

This would create a new DataTable based on filtered values.

If you use DataTable.Select

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



回答2:


You can use condition to check rows exist in addition before casting. System.Linq namespace is required for Any() to work

var rows = values.AsEnumerable().Where
            (row => row.Field<string>("Status") == action);

if(rows.Any()){
    DataTable dt = rows.CopyToDataTable<DataRow>();
 }


来源:https://stackoverflow.com/questions/19449449/how-i-can-filter-a-datatable-with-linq-to-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!