0

I am trying to do a simple calculation and for some reason my return variable is zero. Within my model, I am trying to get a Total of all yes votes and then divide that by the total number of votes. Here are a few relevant classes.

    private int _total = -1;
    public int Total
    {
        get
        {
            if (_total < 0)
            {
                _total = get_total(TopicId);
            }
            return _total;
        }
    }

    private int get_total(int id)
    {
        int itotal = 0;
        int ycount = 0;
        ApplicationDbContext db = new ApplicationDbContext();
        List<Vote> VoteList = db.Votes.Where(t => t.TopicId == id).ToList();
        if (VoteList != null && VoteList.Count > 0)
        {
            //lcount = VoteList.Count();
            foreach (Vote sub in VoteList)
            {

                var c = from v in VoteList
                        where v.Score == true
                        select v.VoteId;
                ycount = c.Count();

                itotal = ycount / VoteList.Count();
            }
        }
        return itotal;
    }

In the for each, if I debug "ycount" is equal to the correct number and Votelist.count is equal to the right number, but itotal is 0. I also attempted to make votelist.count = to a variable, but that produced the same results. I am pretty new to c#, so I'm hoping this is obvious, but what am I missing?

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
MVC_Future_Guru
  • 239
  • 4
  • 15
  • 2
    Note: This has absolutely nothing to do with ASP.NET MVC. There's no MVC-related code in the question at all. This is plain math in plain C#. – David Mar 22 '16 at 19:22
  • 2 points: 1 Please write this: using (ApplicationDbContext db = new ApplicationDbContext()) {....} 2 var c = VoteList.Count(x => x.Score == true); No need to do a select and a count after that. May by I read the code too fast, but where did you use the sub? itotal is always the same result? For each vote, you doing a math action on the same variable VoteList where Score is true (ycount) and the total size of your votelist. – pix Mar 22 '16 at 19:29

1 Answers1

0

ycount is either smaller than or equal to the whole list (VoteList.Count), so the answer will always be 1 if every v.Score is true, or zero for any other case.

If you're looking for the fraction / percent of votes, then you need to change your equation for calculating itotal. Here's an example, if you're asking for an integer percent of votes that "Score":

itotal = (int)((float)ycount / (float)VoteList.Count()) * 100.0); // integer percentage 0 to 100.
Baronz
  • 667
  • 5
  • 16
  • I am trying to get the percent votes and I feel like your question gets me almost all the way there, but itotal is still 0 as a result. By converting back to int am I recreating the initial issue? – MVC_Future_Guru Mar 22 '16 at 19:45