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

Count how many times a field attribute appears in a column

我正在尝试使用 Lambda 或 Linq 计算某个值在 table 的列中出现的次数。

这是我的 Table 属性

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 class 具有 CandidateNoCount 属性。