locked
Find Item. Any, Exists or First? Which one is better? RRS feed

  • Question

  • Hello,

    I need to check if a product with name = "xyz" exists ... I think I can use Any(), Exists() or First().

    Which one is the best option for this kind of situation? Which one has the best performance?

    Thank You,

    Miguel

    Friday, September 14, 2012 4:51 PM

Answers

  • Hi Miguel;

    To your question, "Which one is the best option for this kind of situation? Which one has the best performance?", well first there is not Linq method for Exists(). The Any() will return from its call the minute it finds the first one found where First() finds all the records and just returns the first one. Also First will threw an exception if the sequence is empty. The best would be Any().

      

    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by MDMoura Friday, September 14, 2012 5:34 PM
    Friday, September 14, 2012 5:26 PM

All replies

  • Hi Miguel;

    To your question, "Which one is the best option for this kind of situation? Which one has the best performance?", well first there is not Linq method for Exists(). The Any() will return from its call the minute it finds the first one found where First() finds all the records and just returns the first one. Also First will threw an exception if the sequence is empty. The best would be Any().

      

    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by MDMoura Friday, September 14, 2012 5:34 PM
    Friday, September 14, 2012 5:26 PM
  • well first there is not Linq method for Exists()

    Correct ... I is for List ... So I would use any.

    Thank You,

    Miguel

    Friday, September 14, 2012 5:33 PM
  • Hi,

    As a side note, generally speaking it's best to always choose the construct that express best what you actually want. As shown by Fernando, trying to be clever can hurt as you end up using something that is just not what you actually want (or do it really if you *prooved* what you want has a real issue).


    Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".

    Friday, September 14, 2012 6:22 PM