简体   繁体   English

如何使用LINQ方法语法计算子集合的项目数?

[英]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. 每个问题都可以投票,投票,或者当然不会投票 - 就像在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? 如何使用相同的示例执行此操作?

您可以使用SelectMany

userDbContext.Questions.SelectMany(x => x.QuestionVotes).Count(x => x.IsVoteUp);

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. 然后Sum()将计算这些值的总和。

This LINQ query demonstrates how to do that using 3 level structure tree > branch > leaf as an example . LINQ查询演示了如何使用3级结构tree > branch > leaf作为示例

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. 希望有所帮助。

You can count children using Where like this: 您可以使用以下内容计算儿童:

foreach (YourCollectionType item in datagrid.Items)
{
     var children = datagrid.ItemsSource.OfType<YourCollectionType>().Where(x => x.Item1 == item.Item1 && x.Item2 == item.Item2 && x.Item3 == item.Item3 && x.Item4 == item.Item4);

     item.Results = children.Count();
     Trace.TraceInformation(item.Results.ToString());

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM