问题描述
//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);
是否可以检查查询是否返回任何内容?
喜欢
if(generalFeedbackQuery.Count())....
这似乎可行,但如果您在 Count 上添加手表,它似乎不存在...
推荐答案
查看 anything 是否返回的最好方法是使用 Any().一旦得到任何结果,它就会停止并返回 true,而不是循环遍历所有结果.
(如果您真的想要计数,那么 Count() 确实是正确的方法.我的猜测是 Watch 窗口被它作为扩展方法而感到困惑.您可以显式调用 System.Linq.Enumerable.Count(generalFeedbackQuery) 可能有效.)
问题描述
//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...
推荐答案
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.)