简体   繁体   English

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

[英]Count how many times a field attribute appears in a column

I'm trying to count how many times a value appears in a column on my table using Lambda or Linq. 我正在尝试使用Lambda或Linq计算一个值出现在我的表中的列中的次数。

Here's my Table properties 这是我的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; }
}

So in my controller I'm doing this 所以在我的控制器中

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

For example I want to have something like this 例如我想要这样的东西

CandidateNo      Count
21358              3
21878              4

You need to group by CategoryId . 您需要按CategoryId分组。 Use GroupBy :- 使用GroupBy :-

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

Assuming VoteCan class has CandidateNo & Count properties. 假设VoteCan类具有CandidateNoCount属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM