How to assign variable counter in ForEach Loop Linq C#

I just try some UI Path stuff. I want to assign changes in excel by c#, it’s already works. But my problem is when I want to count how many changes that UI Path do for my excel. It always return 0. So my question is how to count changes in ForEach() C#. Thank you

Here is my code:

int count = 0;
in_dt_DeliveryReport.AsEnumerable().ToList().ForEach(r=>
{
    in_dt_OpsDashboard.AsEnumerable().Where(m=>
    m["AWB Magento"].ToString() == r["AWB"].ToString()).ToList().ForEach(s=>{
        s.SetField<String>("AWB Daily Delivery Order",r["AWB Update"].ToString());
        count += 1;
        in_CountAppendData = count;
    });
});

@gryan
welcome to the forum

we would recommend the check if the approach can be modifed and adapted. It is recommended when using invoke code not to integrate LINQ parts, when it is not needed and can be achieved with straightforward plain code. Also we recommend to look for strategies to reduce the amount of operations.

What we understand from your code:

check for each DeliveryReport - AWB if there are matches on OPSDashboard - AWB Magento
Update all matching OPSDashboards AWB Daily Delivery Order with OpsDashboard AWB Update

first, we would recommend the direction of in_CountAppendData argument. It should be in/out or out that the invoke code also will return it.

inside ForEach(s=>{… we would check if the references to the variables are well kept

at the end of the LINQ we also can count the transported / moved items

So one strategy could be the to filter out the DeliveryReport Rows which had no updates and counting the resulting rows at the end

Another option is to rewrite the code to more plain C# by using

foreach (DataRow r in in_dt_DeliveryReport.AsEnumerable())
{
    //
}

for the outer loop

Regarding the update we also have strategies to organize it by LookUp Helper Dictionaries and then count the Dictionary entries

if I change direction of in_CountAppendData argument into in/out or out I got an error

Hi,

I think it’s needed to use the argument outside the LINQ expression, as the following.

int count = 0;
in_dt_DeliveryReport.AsEnumerable().ToList().ForEach(r=>
{
    in_dt_OpsDashboard.AsEnumerable().Where(m=>
        m["AWB Magento"].ToString() == r["AWB"].ToString()).ToList().ForEach(s=>{
        s.SetField<String>("AWB Daily Delivery Order",r["AWB Update"].ToString());
        count++;
    });
});
out_CountAppendData = count;

Regards,

1 Like

Thank you, it’s work :slight_smile:

1 Like

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