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)
  • 2
    \$\begingroup\$ please provide more information on what you want improved. and probably more surrounding code for context. \$\endgroup\$
    – Malachi
    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
    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
    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\$ Jan 6, 2014 at 15:54

1 Answer 1


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)

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

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

Your Answer

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

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