简体   繁体   English

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

[英]ASP.NET Core MVC Calculate percentage of ENUM

How can I calculate the percentage of occurences from a ENUM?如何计算 ENUM 的出现百分比? I have a list of bookings and I have 2 different types of sockets in my ENUM.我有一个预订清单,我的 ENUM 中有 2 种不同类型的 sockets。 For example if booking_1 has type_1, booking_2 has type_1 and then booking_3 has type_2 I should get in my View table that type_1 is used 66.6% and type_2 33.3%例如,如果 booking_1 有 type_1,booking_2 有 type_1,然后 booking_3 有 type_2 我应该在我的视图表中使用 type_1 66.6% 和 type_2 33.3%

Here is my ENUM:这是我的枚举:

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

Here is the ViewModel:这是视图模型:

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

And my problem is with the Controller.我的问题是 Controller。 I somehow need to use a loop to calculate the percentage of each occurence of my ENUM types in my bookingsList but I have no idea how:我不知何故需要使用循环来计算我的 ENUM 类型在我的 bookingsList 中每次出现的百分比,但我不知道如何:

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

As I understand you want to calculate percentage per connectorType for all bookings.据我了解,您想计算所有预订的每个连接器类型的百分比。 Create a list with these two connector and calculate percentage as below:使用这两个连接器创建一个列表并计算百分比如下:

List<ConnectorTypeEvaluationViewModel> connectorTypeEvaluationViewModel = new List<ConnectorTypeEvaluationViewModel>();

connectorTypeEvaluationViewModel.Add(new ConnectorTypeEvaluationViewModel
            {
                connectorType = ConnectorType.Type2Plug,
                connectorPercentage = (bookingsList.Count(s => s.connectorType==ConnectorType.Type2Plug)/Convert.ToDouble(bookingsList.Count()))*100
            });

connectorTypeEvaluationViewModel.Add(new ConnectorTypeEvaluationViewModel
            {
                connectorType = ConnectorType.CCSCombo2Plug,
                connectorPercentage = (bookingsList.Count(s => s.connectorType== ConnectorType.CCSCombo2Plug) / Convert.ToDouble(bookingsList.Count())) * 100
            });

Percentage calculation is (i / n) * 100 where n is the total number of observations and i is example the number of Type2Plug.百分比计算为(i / n) * 100 ,其中n是观察总数, i是 Type2Plug 的数量。

Could probably be optimize somehow, maybe by using GroupBy .可能会以某种方式进行优化,也许是通过使用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();
}

EDIT编辑

I create a generic way to calculate percentage based on a property我创建了一种基于属性计算百分比的通用方法

public static Dictionary<TProperty, double> Percentage<T, TProperty>(this IEnumerable<T> source, Expression<Func<T,TProperty>> selector)
{
    var dict = new Dictionary<TProperty, double>();
    Func<T,TProperty> func = selector.Compile();

    var list = source.ToList();
    var groups = list.GroupBy(func).ToList();
    double total = list.Count;

    foreach(var group in groups)
    {
        double groupCount = group.Count();
        var percentage = (groupCount / total) * 100;
        dict.Add(group.Key, percentage);
    }

    return dict;
}

Usage用法

var dict = list.Percentage(x => x.SomeProperty);

https://dotnetfiddle.net/Hqy9GV https://dotnetfiddle.net/Hqy9GV

Thanks a lot for the help.非常感谢您的帮助。 I managed to make a foreach loop to add every type so if I need more types i don't have to add all of them manually: Here is the code:我设法创建了一个 foreach 循环来添加每种类型,所以如果我需要更多类型,我不必手动添加所有类型:这是代码:

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);
            List<ConnectorTypeEvaluationViewModel> connectorsList = new List<ConnectorTypeEvaluationViewModel>();
            var connectors = Enum.GetValues(typeof(ConnectorType)).Cast<ConnectorType>();
            foreach (var item in connectors)
            {
                connectorsList.Add(new ConnectorTypeEvaluationViewModel
                {
                    connectorType = item,
                    connectorPercentage = (bookingsList.Count(s => s.connectorType == item) / Convert.ToDouble(bookingsList.Count())) * 100
                });
            }

            return View(connectorsList);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM