Vishal
Vishal

Reputation: 6368

How do you convert these nested foreach to linq

Here is my query with nested foreach:

foreach (Order order in xOrders)
{
    foreach (OrderItemDetail oid in order.OrderItemDetails)
    {
        db.Entry(oid).Reload();
    }

    foreach (Dispatch dispatch in order.Dispatches)
    {
        foreach (DispatchItemDetail did in dispatch.DispatchItemDetails)
        {
            db.Entry(did).Reload();
        }

        db.Entry(dispatch).Reload();
    }

    db.Entry(order).Reload();
}

Now, I want to convert that to pure linq, so I am safer atleast for the errors such as Enumeration cannot continue because Collection was changed.

I know, if there is 1 foreach I can convert it to LINQ like:

foreach query:

foreach (Order order in xOrders)
{
    db.Entry(order).Reload();
}

LINQ query:

xOrders.ToList().ForEach(x => db.Entry(x).Reload());

But I want to know how you can do that for Nested foreach as shown in the first code block....

Upvotes: 0

Views: 177

Answers (1)

Sivaprasad derangula
Sivaprasad derangula

Reputation: 1169

The ForEach takes a delegate as a parameter. So you can write static method or anonymous function. I'm writing with Anonymus method. But the way you do above is the best way than using ForEach()

 xOrders.ToList().ForEach((x) => {
     x.OrderItemDetails.ToList().ForEach(o => db.Entry(o).Reload());
     x.Dispatches.ToList().ForEach((D) => {
       D.DispatchItemDetails.ToList().ForEach(DI => db.Entry(DI).Reload());
       db.Entry(D).Reload();
     });
     db.Entry(x).Reload();
   });

Upvotes: 3

Related Questions