3
\$\begingroup\$

Can this be improved?

foreach (Gift gift in usedGifts)
{
    foreach (GiftTransaction GiftTransaction in gift.GiftTransactions)
    {
        if (!string.IsNullOrEmpty(giftTransaction.GiftId) &&
            !orderList.Where(b => b.GiftId == giftTransaction.GiftId).Any())
        {
            Order order = OrderHelper.PopulateSingleOrder(orderRepository, sessionRepository, giftTransaction.GiftId);
            if (order != null)
                orderList.Add(order);
        }
    }
    giftReferenceList.Add(gift.GiftReference);
}
\$\endgroup\$
4
  • 2
    \$\begingroup\$ please provide more information on what you want improved. and probably more surrounding code for context. \$\endgroup\$
    – Malachi
    Commented Jan 6, 2014 at 15:09
  • 1
    \$\begingroup\$ Optimizing for performance? Your question is not really clear here. Fairly common refactoring ideas could be found in questions like stackoverflow.com/questions/2433679/… \$\endgroup\$
    – shivsky
    Commented Jan 6, 2014 at 15:24
  • \$\begingroup\$ I want to improve the speed for the query... but I will try to provide more details soon \$\endgroup\$
    – datatest
    Commented Jan 6, 2014 at 15:28
  • 1
    \$\begingroup\$ You can replace the line !orderList.Where(b => b.GiftId == giftTransaction.GiftId).Any() with !orderList.Any(b => b.GiftId == giftTransaction.GiftId) for what it's worth. \$\endgroup\$ Commented Jan 6, 2014 at 15:54

1 Answer 1

7
\$\begingroup\$

I'm not sure if it will make your query faster but here is my take on it:

If I read the code correctly you want to create orders for all gift transactions related to gift ids which are not covered by an order yet.

usedGifts.SelectMany(g => g.GiftTransactions)
         .Select(gt => gt.GiftId)
         .Where(gi => !string.IsNullOrEmpty(gi))
         .Except(orderList.Select(o => o.GiftId)) // This will yield all gift ids which are not covered by an order
         .Select(gi => OrderHelper.PopulateSingleOrder(orderRepository, sessionRepository, gi))  // generate the orders
         .Where(o => o != null)
         .ToList();

Unfortunately this requires an extra pass over the usedGifts list to add all the references

giftReferenceList.AddRange(usedGifts.Select(g => g.GiftReference));
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.