Linq计数返回结果 [英] 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?
像
if(generalFeedbackQuery.Count())....
这似乎可行,但是如果您在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.
(如果您确实想要计数,那么Count()
确实是正确的方法.我的猜测是Watch窗口由于是扩展方法而感到困惑.您可以显式调用System.Linq.Enumerable.Count(generalFeedbackQuery)
,这可能会起作用. )
(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.)
这篇关于Linq计数返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!