I have the following LINQ query:
Manager mngr = (from tr in DataContext.Manager
where tr.Name = "Jones").FirstOrDefault();
How can I check if the query did return 1 record
as I cannot do .Count to get the count.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First of all, that is not a valid query. When you use the query syntax (
from blah in blah ...), you must have aselectclause. It should be more like:To answer your question, calling
FirstOrDefault()on your query will return the first result of the query or the default value for the type (most likelynullin this case). For what you’re going for, this won’t be an adequate use since the query may contain more than one result.If you wish to verify that the query only returns a single result, you should use the
SingleOrDefault()method instead. It will return either the one item produced by the query, the default valuenullif it was empty or throw an exception if there was more than one item.If you don’t want to throw an exception, it may be easier to just throw the first two results into a list and verify that you only have one.