How to get a subset DataTable from another DataTable filtered by few column values?

爷,独闯天下 提交于 2019-12-08 03:49:24

问题


The problem I have is, my search criteria is:

Row["colName"] != "abc"  AND 
Row["colName"] != "def"  AND 
Row["colName"] != "ghic"  AND 
Row["colName"] != "klm"  AND
Row["colName"] != "xyz"  AND 
Row["colName"] != "mnp"  etc..

in other words, after my research I found something about DefaultView of the DataTable and RowFilter, but Rowfilter seems to filter only by one value.

My situation is I need to filter by a bunch of values.

Thanks


回答1:


You could use Linq-To-DataTable and a collection of values to exclude.

Query Syntax:

string[] exclude = { "def", "ghic", "klm", "xyz", "mnp" };
var filteredRows = from row in dataTable.AsEnumerable()
                   where !exclude.Contains(row.Field<string>("colName"))
                   select row;
DataTable result = filteredRows.CopyToDataTable();

Method Syntax:

result = dataTable.AsEnumerable()
    .Where(r => !exclude.Contains(r.Field<string>("colName")))
    .CopyToDataTable();



回答2:


You can use AsEnumerable to get an IEnumerable<DataRow> of the rows, and do a Where on that.

var criteria = new List<string>();
criteria.Add("abc");
criteria.Add("def");
criteria.Add("ghic");
//etc

var filteredRows = myDataTable.AsEnumerable()
    .Where(row => !criteria.Contains(row["colName"].ToString()));


来源:https://stackoverflow.com/questions/27259631/how-to-get-a-subset-datatable-from-another-datatable-filtered-by-few-column-valu

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