I need the most efficient way to get the value of the searchName, or if null return searchName. I am returning just a single string, so maybe I should search itemRepository.Item instead of Items

return itemRepository.Items()
                    .Where(i => i.Name.Contains(searchName))
                    .Select(i => i.Value)
                    .FirstOrDefault() ?? searchName;
  • \$\begingroup\$ Why is Items a method rather than a property (as evidenced by the ())? Other than that question, this seems exactly the canonical way I'd do what you're looking for. \$\endgroup\$ Commented Mar 18, 2013 at 15:56
  • \$\begingroup\$ Yeah it is a bit weird, but its calling an API, which returns a set of Items, I can also pass in a filter and a sort to the method. I just feel like I am looping one too many times \$\endgroup\$
    – Spooks
    Commented Mar 18, 2013 at 16:00
  • \$\begingroup\$ 1. You should not be concerned with the internal workings of LINQ - the designers have gone through great lengths to make it as optimal as possible. There are no direct loops in your code. 2. That being said, I only see a single loop - the one that goes over all items and pulls out the Value of those that contain searchName in its Name. \$\endgroup\$ Commented Mar 18, 2013 at 16:05
  • 1
    \$\begingroup\$ You can combine the .Select() and the .FirstOrDefault(), but other than that, there's nothing else you can do to this query. \$\endgroup\$
    – Bobson
    Commented Mar 18, 2013 at 16:32
  • \$\begingroup\$ @Bobson combine them how? \$\endgroup\$
    – Spooks
    Commented Mar 18, 2013 at 16:47

1 Answer 1


As long as Items() returns an IQueryable<Item> directly from the database, then this code is just about as fast as you can get it. If not, I think your Items() method will be the main bottleneck in this code.

From your comment it sounds like Items() is indeed trying to do more work than necessary. You should either directly reference the IQueryable collection of the repository and bypass the Items() method or focus your efforts on improving the efficiency of that method.


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.