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?
In LINQ, you can count the total number of elements present in the given sequence by using the Count Method. This method returns the total number of elements present in the given sequence.
You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.
You can use SelectMany
:
userDbContext.Questions.SelectMany(x => x.QuestionVotes).Count(x => x.IsVoteUp);
This LINQ
query demonstrates how to do that using 3 level structure tree
> branch
> leaf
as an example.
So the code below gives you the number of the leaves from all branches of all trees (all or only colored with the given color):
public class Calculator
{
public int CountAllLeafsOn(List<Tree> trees, string сolor = null)
{
// Count the leafs (all from all branches of all trees, or only if they are colored with the provided color)
return сolor == null
? trees.Sum(tree => tree.Branches.Sum(branch => branch.Leaves.Count))
: trees.Sum(tree => tree.Branches.Sum(branch => branch.Leaves.Count(leaf => leaf.Color.Equals(сolor))));
}
}
public class Tree
{
public List<Branch> Branches { get; set; }
}
public class Branch
{
public List<Leaf> Leaves { get; set; }
}
public class Leaf
{
public string Color { get; set; }
}
Hope that helps.
It must work:
int number = userDbContext.Questions
.Select(x => x.QuestionVotes.Count(y => y.IsVoteUp))
.Sum();
It will get the count of filtered child items for each parent. Then Sum()
will compute the sum of these values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With