Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 399
user1298925 Avatar asked Nov 25 '25 20:11

user1298925


2 Answers

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();
like image 140
Tim Schmelter Avatar answered Nov 28 '25 09:11

Tim Schmelter


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()));
like image 38
Dave Zych Avatar answered Nov 28 '25 08:11

Dave Zych



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!