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

Yul*_*ian 10 c# linq methods syntax count

假设我有一个模式,代表问题实体.每个问题都可以投票,投票,或者当然不会投票 - 就像在StackOverflow中一样.我想获得给定用户的投票数量.

int number = (from q in userDbContext.Questions
              from qv in q.QuestionVotes
              where qv.IsVoteUp
              select qv).Count();
Run Code Online (Sandbox Code Playgroud)

我想编写相同的查询,但使用方法语法.如何使用相同的示例执行此操作?

Sel*_*enç 21

你可以使用SelectMany:

userDbContext.Questions.SelectMany(x => x.QuestionVotes).Count(x => x.IsVoteUp);
Run Code Online (Sandbox Code Playgroud)


Dmi*_*lov 5

此查询以3 级结构>>为例演示LINQ了如何执行此操作。treebranchleaf

\n\n

因此,下面的代码给出了所有树的所有分支的叶子数量(全部或仅用给定颜色着色):

\n\n
public class Calculator\n{\n    public int CountAllLeafsOn(List<Tree> trees, string \xd1\x81olor = null)\n    {\n        // Count the leafs (all from all branches of all trees, or only if they are colored with the provided color)\n        return \xd1\x81olor == null \n            ? trees.Sum(tree => tree.Branches.Sum(branch => branch.Leaves.Count)) \n            : trees.Sum(tree => tree.Branches.Sum(branch => branch.Leaves.Count(leaf => leaf.Color.Equals(\xd1\x81olor))));\n    }\n}\n\npublic class Tree\n{\n    public List<Branch> Branches { get; set; }\n}\n\npublic class Branch\n{\n    public List<Leaf> Leaves { get; set; }\n}\n\npublic class Leaf\n{\n    public string Color { get; set; }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

希望有帮助。

\n