Yulian Yulian - 1 year ago 67
C# Question

How do I count the number of child collection's items using LINQ Method Syntax?

Let's say I have a schema, representing Question entities. Each question can be voted up, voted down or, of course, not voted at all - just like here in StackOverflow. I want to get the number of voteups for a given user.

int number = (from q in userDbContext.Questions
from qv in q.QuestionVotes
where qv.IsVoteUp
select qv).Count();

I want to write the same query, but using Method Syntax. How do I do this with the same example?

Answer Source

You can use SelectMany:

userDbContext.Questions.SelectMany(x => x.QuestionVotes).Count(x => x.IsVoteUp);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download