I need to find data from data table with multiple values from one column only.
Below is an example:
var Value = (from r in datatable.AsEnumerable()
where r.Field<string>(ColumnName).Contains("test1,test2")
select r ).ToList();
Here ColumnName is my Datatable's column name and "test1, test2" are different values ( number of values are dynamic and have "," as delimiter ).
I want to make this Linq query which returns all records from datatable which have values equal to "test1
" and "test2
".
Edit :
Above LINQ Query returns result like below SQL Query.
Select * from Table where ColumnName in ('test1','test2')
Use Split
+ Join
:
IEnumerable<string> values = "test1,test2".Split(',');
var matchingRows = from row in datatable.AsEnumerable()
join value in values
on row.Field<string>(ColumnName) equals value
select row;
DataTable tblResult = matchingRows.CopyToDataTable(); // or ToList
For the sake of completeness, the less efficient but more natural approach using Contains
:
var matchingRows = from row in datatable.AsEnumerable()
where values.Contains(row.Field<string>(ColumnName))
select row;