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

本文关键字:字段 属性 计算 | 更新日期: 2023-09-27 18:17:44

我正在尝试使用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();
}

例如,我想要这样写

CandidateNo      Count
21358              3
21878              4

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

CategoryId分组。使用GroupBy: -

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

假设VoteCan类有CandidateNo &Count属性。