How to use LINQ expression to update "Status" column in the data table based on condition?

Hello,

I have a data table, dt as follow. There are 3 columns: Column1, Column2, and Status.

Column1 Column2 Status
A 1 No
B 2 No
A 3 No
C 4 No
B 5 No

I would like to use LINQ expression to update the value of status column to “Yes” if Column1 = A and Column2 = 3.

In UiPath, I use Assign activity. In “Save To” field, I write LINQ expression → dt.AsEnumerable.where(function(row) row.field(Of string)(“Column1”).Equals(“A”) And row.field(Of string)(“Column 2”).Equals(“3”)).copytodatatable.row(0).item(“Status”). In “Value to save” filed, I write “Yes”.

The above way does not update status value to Yes. How to solve this issue?

Thanks.

Hi @peter.tun

Try the below code in Invoke Code:

For Each row In dt.AsEnumerable()
    If row.Field(Of String)("Column1").Equals("A") AndAlso row.Field(Of Double)("Column2") = 3 Then
        row("Status") = "Yes"
    Else
        row("Status") = "No"
    End If
Next

Invoked Arguments:
dt → In/Out

Check the below flow for better understanding.

=> Read Range Workbook
image
Output → dt

=> Use below code in Invoke Code:

For Each row In dt.AsEnumerable()
    If row.Field(Of String)("Column1").Equals("A") AndAlso row.Field(Of Double)("Column2") = 3 Then
        row("Status") = "Yes"
    Else
        row("Status") = "No"
    End If
Next

Invoke Code Arguments:

=> Write Range Workbook dt back to excel.
image

Sequence1.xaml (7.7 KB)

Hope it helps!!

Hi @peter.tun

(From row In dt.AsEnumerable() Where row.Field(Of String)("Column1") = "A" AndAlso row.Field(Of String)("Column2") = "3" Select row).ToList().ForEach(Sub(r) r("Status") = "Yes")

@peter.tun

dt = dt.AsEnumerable().Select(Function(row) 
    If row.Field(Of String)("Column1") = "A" AndAlso row.Field(Of Int32)("Column2") = 3 Then
        row.SetField("Status", "Yes")
    End If
    Return row
End Function).CopyToDataTable()

Please put this expression in invoke code activity
dt as In/Out argument

Note:row.Field(Of Int32)(“Column2”) -->Please check the datatype of Column2 in your excel it may be Double,String or Int32


Output:
image

Hi @peter.tun

=> Read Range Workbook
image
Output → dt

=> Use below code in Invoke Code:

For Each row In dt.AsEnumerable()
    If row.Field(Of String)("Column1").Equals("A") AndAlso row.Field(Of Double)("Column2") = 3 Then
        row("Status") = "Yes"
    Else
        row("Status") = "No"
    End If
Next

Invoke Code Arguments:

=> Write Range Workbook dt back to excel.
image

Sequence1.xaml (7.7 KB)

Hope it helps!!

Also refer on downer part, where updating a subset is described

Thank you for your suggestion.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.