Ife Ologbese Ife Ologbese - 2 months ago 5
C# Question

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.

Here's my Table properties

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

Answer

You need to group by CategoryId. Use 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.

Comments