2015-10-15 56 views
0

我正在尝试使用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 

回答

0

您需要组由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性能。