ASP.NET Core MVC计算ENUM的百分比

如何计算ENUM发生的百分比?我有一份预订清单,我的ENUM中有2种不同类型的插座。例如,如果booking_1的类型为_1,booking_2的类型为_1,然后booking_3的类型为_2,我应该在“视图”表中看到type_1的使用率为66.6%,type_2为33.3%

这是我的ENUM:

        namespace WebApplication.Models
{
    public enum ConnectorType
    {
        [Display(Name = "Type 2-Plug")]
        Type2Plug,
        [Display(Name = "CCS Combo 2-Plug")]
        CCSCombo2Plug
    }
}

这是ViewModel:

namespace WebApplication.ViewModels
{
    public class ConnectorTypeEvaluationViewModel
    {
        [Display(Name = "Anschlusstyp")]
        public ConnectorType connectorType { get; set; }
        [Display(Name = "Prozentsatz")]
        public double connectorPercentage { get; set; }
    }
}

我的问题是控制器。我不知何故需要使用一个循环来计算我的bookingsList中我的ENUM类型每次出现的百分比,但是我不知道如何:

namespace WebApplication.Controllers
{
   public class ConnectorTypeEvaluationController : Controller
   {
       private IMemoryCache _cache;
       public ConnectorTypeEvaluationController(IMemoryCache cache)
       {
           _cache = cache;
       }
       public IActionResult Index()
       {
           List<Booking> bookingsList;
           _cache.TryGetValue("key", out bookingsList);
           double total = bookingsList.Count;
           connectorType = ??;
           connectorPercentage = ??;
           return View();
       }
   }
}
评论
  • 念念不忘
    念念不忘 回复

    Percentage calculation is (i / n) * 100 where n is the total number of observations and i is example the number of Type2Plug.

    Could probably be optimize somehow, maybe by using GroupBy.

    public IActionResult Index()
    {
       List<Booking> bookingsList;
       _cache.TryGetValue("key", out bookingsList);
    
       double type2PlugCount = bookingsList.Count(x => x.connectorType == ConnectorType.Type2Plug);
       double cCSCombo2PlugCount = bookingsList.Count(x => x.connectorType == ConnectorType.CCSCombo2Plug);
       double total = bookingsList.Count;
    
       var type2PlugPercentage = (type2PlugCount / total) * 100;
       var cCSCombo2PlugPercentage = (cCSCombo2PlugCount / total) * 100;
    
       return View();
    }