Ife Ologbese Ife Ologbese - 1 year ago 71
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
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>();
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 Source

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

Assuming VoteCan class has CandidateNo & Count properties.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download