C# 如何使用 Linq 过滤数据表到数据表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19449449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How I can filter a dataTable with Linq to datatable?
提问by Tarasov
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.
嗨,我如何使用 linq to datatable 过滤数据表?我有一个 DropDownList,在那里我可以选择 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);
}
采纳答案by Habib
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);
回答by Nayas Subramanian
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
}
回答by Maghalakshmi Saravana
To Retrieve the DataTable based on filtering the list of item.(i.e.,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