How to create new Columns based on existing DataColumns | UiPath
While dealing with datatables, we come across scenarios where we need to create new DataColumns from the data in existing DataColumns, based on some business logic.
Let’s see how we can achieve it in UiPath through an example..
Example
Scenario ->
Let’s assume an input DataTable “dt_StudentMarks” which has 4 columns [Name, Physics, Chemistry, Maths], as shown below : -
The requirement is to add 2 new columns [Total ,Status], where : -
Total = Physics + Chemistry + Maths
Status = If Total > 75 , “Pass” ; else “Fail”
Solution ->
Thinking of using For Loops?? Let’s explore another super easy way to do it!
We will use an overload (version) of “DataColumnCollection.Add()” method. It will Add a DataColumn with the specified Name and Type. The interesting part is the values in the DataColumn will be defined by the expression string! Let’s make it work!!
Step 1 :- (Add TotalMarks column)
We will use “Invoke Method” activity to invoke the “Add” method on column collection “dt_StudentMarks.Columns”. The Parameters property has to be used to define the name as “TotalMarks”, and type as Int32. The expression string would be “Physics + Chemistry + Maths”. (It represents the 3 columns to be added)
Now, let’s have a look below at the updated DataTable. You can observe that “TotalMarks” column got added to the right, with each value as the sum of other three column values! Simple, isn't it?
Step 2 :- (Add Status column)
Now let’s repeat the previous step with the required twist. Our new column name should be “Status” of type String. The expression string would be “IIF(TotalMarks > 75, ‘Pass’, ‘Fail’)”
Result ->
We just used 2 invoke method activities to get the job done! Now, let’s observe below result. “TotalMarks” and “Status” column got added to our DataTable with the required values! Sweet!!
You can learn more about creating such expressions from official Microsoft documentation.
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..