Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 493
Yulian Avatar asked Aug 04 '14 08:08

Yulian


People also ask

How do you count in LINQ?

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.

What collections can LINQ be used with?

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.


3 Answers

You can use SelectMany:

userDbContext.Questions.SelectMany(x => x.QuestionVotes).Count(x => x.IsVoteUp);
like image 87
Selman Genç Avatar answered Oct 14 '22 10:10

Selman Genç


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.

like image 30
Dmitry Pavlov Avatar answered Oct 14 '22 09:10

Dmitry Pavlov


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.

like image 38
Farhad Jabiyev Avatar answered Oct 14 '22 11:10

Farhad Jabiyev