C# 计算字段属性在列中出现的次数

C# 计算字段属性在列中出现的次数,c#,asp.net-mvc,linq,count,C#,Asp.net Mvc,Linq,Count,我试图使用Lambda或Linq计算一个值在表中的列中出现的次数 这是我的桌子 public class Vote { [Key] public int VoteId { get; set; } public int CandidateId { get; set; } public int CategoryId { get; set; } public string Id { get; set; } public int Participan

我试图使用Lambda或Linq计算一个值在表中的列中出现的次数

这是我的桌子

public class Vote
{
    [Key]
    public int VoteId { get; set; }

    public int CandidateId { get; set; }

    public int CategoryId { get; set; }

    public string Id { get; set; }
    public int ParticipantId { get; set; }
    public DateTime datecreated { get; set; }
}
所以在我的控制器里,我在做这个

public ActionResult Index(int? CategoryId, string Id)
{
    List<VoteCan> agc = new List<VoteCan>();
    if(CategoryId.HasValue)
    {
        var allcategory = db.Votes.ToList().FindAll(x => (x.CategoryId == CategoryId.Value) && (x.Id == Id)).ToList();
        //I want to count how many Candidates are in the Votes table using the candidateId
    }

    return View();
}
您需要按类别ID进行分组。使用:-

假设VoteCan类具有CandidateNo和Count属性

CandidateNo      Count
21358              3
21878              4
List<VoteCan> results = db.Votes.GroupBy(x => x.CandidateId)
                      .Select(x => new VoteCan
                                  {
                                      CandidateNo = x.Key,
                                      Count = x.Count()
                                  }).ToList();