Sunday, April 17, 2011

Linq Count Returned Results

//Feedback Check
var generalFeedbackQuery = from feedbackElements in xml.Elements("feedback")
                           select new
                           {
                               Feedback = feedbackElements.Element("general").Value,
                               PostiveFeedback = feedbackElements.Element("positive").Value,
                               NegativeFeedback = feedbackElements.Element("negative").Value
                           };

Assert.AreEqual(actual.feedback, generalFeedbackQuery.ElementAt(0).Feedback);
Assert.AreEqual(actual.positiveFeedback, generalFeedbackQuery.ElementAt(0).PostiveFeedback);
Assert.AreEqual(actual.negativeFeedback, generalFeedbackQuery.ElementAt(0).NegativeFeedback);

Is it possible to check whether the query returned anything?

Like

if(generalFeedbackQuery.Count())....

This seems to work, but if you add a watch on the Count it doesn't seem to exist...

From stackoverflow
  • The best way of seeing whether or not anything was returned is to use Any(). That will stop and return true as soon as it gets any results, rather than looping through all of them.

    (If you actually want the count, then Count() is indeed the right way to go. My guess is that the Watch window is confused by it being an extension method. You could explicitly call System.Linq.Enumerable.Count(generalFeedbackQuery) which may work.)

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.