简体   繁体   English

如何使用 Linq 过滤数据表到数据表?

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

hi how i can filter a datatable with linq to datatable?嗨,我如何使用 linq to datatable 过滤数据表? I have a DropDownList and there I can select the value of the Modul Column.我有一个 DropDownList,在那里我可以选择 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);
}

You are better of using DataTable.Select method, but if you have to use LINQ then you can try:您最好使用DataTable.Select方法,但如果您必须使用 LINQ,那么您可以尝试:

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

This would create a new DataTable based on filtered values.这将根据过滤的值创建一个新的DataTable

If you use DataTable.Select如果您使用DataTable.Select

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

You can use condition to check rows exist in addition before casting.您可以在转换之前使用条件来检查行是否存在。 System.Linq namespace is required for Any() to work 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
}

To Retrieve the DataTable based on filtering the list of item.基于过滤项目列表检索数据表。 (ie,if any of the list item is present in datatable, that matched result will received. (即,如果数据表中存在任何列表项,则将收到匹配的结果。

 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