C# 我如何计算子集合的数量';使用LINQ方法语法的项目?

C# 我如何计算子集合的数量';使用LINQ方法语法的项目?,c#,linq,methods,syntax,count,C#,Linq,Methods,Syntax,Count,假设我有一个模式,表示问题实体。每个问题都可以被投赞成票,也可以被投反对票,当然,也可以根本不被投票——就像这里的StackOverflow一样。我想获取给定用户的VoteUp数 int number = (from q in userDbContext.Questions from qv in q.QuestionVotes where qv.IsVoteUp select qv).Count(); 我想编写

假设我有一个模式,表示问题实体。每个问题都可以被投赞成票,也可以被投反对票,当然,也可以根本不被投票——就像这里的StackOverflow一样。我想获取给定用户的VoteUp数

int number = (from q in userDbContext.Questions
              from qv in q.QuestionVotes
              where qv.IsVoteUp
              select qv).Count();
我想编写相同的查询,但使用方法语法。如何使用相同的示例执行此操作?

它必须工作:

  int number =  userDbContext.Questions
                             .Select(x => x.QuestionVotes.Count(y => y.IsVoteUp))
                             .Sum();

它将获得每个父项的已筛选子项的计数。然后
Sum()
将计算这些值的总和。

您可以使用
SelectMany

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

您可以使用以下方法计算儿童人数:

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());

}
foreach(datagrid.Items中的YourCollectionType项)
{
var children=datagrid.ItemsSource.OfType()。其中(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());
}

这个
LINQ
查询演示了如何使用3级结构
分支
作为一个示例

因此,下面的代码为您提供了所有树的所有分支的叶数(全部或仅使用给定颜色着色):

公共类计算器
{
public int CountAllLeafsOn(列表树,字符串c color=null)
{
//计算树叶数量(所有树木的所有树枝上的树叶,或者仅当它们使用提供的颜色着色时)
返回c color==null
?trees.Sum(tree=>tree.branchs.Sum(branch=>branch.Leaves.Count))
:trees.Sum(tree=>tree.branchs.Sum(branch=>branch.Leaves.Count(leaf=>leaf.Color.Equals(c Color)));
}
}
公共类树
{
公共列表分支{get;set;}
}
公营部门
{
公共列表离开{get;set;}
}
公共类叶
{
公共字符串颜色{get;set;}
}
希望有帮助

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; }
}