How to filter a datatable based on multiple values | UiPath
If we have to filter records from datatable based on single value, it can be easily done using the “Filter Data Table” activity. But, things become bit complicated when we have an array of values as the filter criteria. Well, it can also be easily done using DataTable.Select method !
Let’s see how we can achieve it in UiPath through an example…
Example Scenario
Let’s consider an input data file (Fig 1) stored in datatable variable dt_InputData. The filter criteria for “Type” column has been stored in array variable arr_TypeFilter (Fig 2).
Solution
The format of using Datatable.Select method is shown below:-
expression = "ColumnName IN ('String1', 'String2', 'String3')"
datatable.Select(expression).CopyToDataTable
So, we just need to bring the array variable into above format to be used in the select method! Simple.
Step 1: Use String.Join method to convert the arr_TypeFilter into a string variable str_ArrTypeFilter with format -> Mammal’,’Reptiles’,’Amphibian
str_ArrTypeFilter = String.Join("','",arr_TypeFilter)
Step 2: Use the above string str_ArrTypeFilter in the datatable.select method as shown below. Then, assign value back to dt_InputData.
dt_InputData = dt_InputData.Select("[Type] IN ('" + str_ArrTypeFilter + "')").CopyToDataTable
Result
The updated datatable dt_InputData can now be written into excel using the “Write Range” activity and it will have the filtered values !
NOTE: We can also get the records which do not match the given filter by just replacing “IN” with “NOT IN”!
Feel free to Follow me here for more such easy to understand content. I am also available on LinkedIn :-)
Thank you for your time !! See you soon..