从列表中获取每个项目的百分比<ListItem>

Get % of Each item from List<ListItem>

我需要计算列表中每个项目占项目总数的百分比。假设我的列表包含三个项目:

  1. 是的,计数为 0
  2. 否,计数为 0
  3. 不能说,有数1

optionsList.Count: 3

foreach (ListItem opt in optionsList)
{
    double cnt = Convert.ToDouble(opt.Value);
    double totalCnt = Convert.ToDouble(optionsList.Count);
    double percentage = Math.Truncate((cnt/ totalCnt) * 100);

    results.InnerHtml += percentage.ToString() + " % " + opt.Text + " <br/>" + " <br/>";
}

输出:

在上面的结果中,如果 yes 和 no 都是 0 那么结果应该是 100% 但它显示 33%。

试试这个。这里的关键点是你应该除以计数成员的 SUM,而不是列表条目的计数。在您的示例中,totalCount 始终为 3,因此 1/3*100 = 33%。实际上 totalCount 应该是 0 + 0 + 1 所以你最终得到 1/1*100 = 100%.

namespace ConsoleApplication
{
    public class Test
    {
        public string name { get; set; }
        public int count { get; set; }
    }


    class Program
    {
        static void Main(string[] args)
        {
                List<Test> testList = new List<Test>();
                testList.Add(new Test { name = "yes", count = 1 });
                testList.Add(new Test { name = "no", count = 0 });
                testList.Add(new Test { name = "can't say", count = 3 });


                var totalCount = testList.Sum(c => c.count);

                foreach(var item in testList)
                {
                    Console.WriteLine(string.Format("{0} {1}", (decimal)item.count / totalCount * 100, item.name));
                }

                Console.ReadKey();
        }
    }
}