嗨,如何使用 LINQ 到 DataTable 过滤数据表?我有一个下拉列表,在那里我可以选择模块列的值。现在我想用这个模列过滤数据表。
这是我的数据表结构:
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);
在强制转换之前,可以使用条件检查行是否存在。System.Linq 命名空间是 Any() 工作所必需的
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