как показать количество пользователей по возрастным группам в элементе управления графиком в Asp.net MVC - PullRequest
0 голосов
/ 07 мая 2018

как показать количество пользователей по возрастным группам в элементе управления диаграммой в Asp.net MVC?

Вот логика, позволяющая определить возрастную группу и количество пользователей в каждой возрастной группе, но то, как ее использовать в элементе управления диаграммой, может сбить меня с толку. Пожалуйста, предложите, нужно ли мне добавить другой класс или нужно изменить запрос LINQ с помощью групповой операции.

 public List<AgeVM> getuserAge()
            {
                List<AgeVM> listAgeVM = new List<AgeVM>();
                int countteen = 0;
                int countYoung = 0;
                int countMedioker = 0;
                int countSenior = 0;
                var res = from a in _Registrationrepository.GetAll()
                          select new
                          {
                              age = a.DOB,
                              name = a.FirstName,

                          };
                foreach (var item in res)
                {

                    AgeVM ageVM = new AgeVM();

                    var day = item.age.Day;
                    var month = item.age.Month;
                    var year = item.age.Year;
                    var currentDay = System.DateTime.Now.Day;
                    var currentMonth = System.DateTime.Now.Month;
                    var currentYear = System.DateTime.Now.Year;
                    if (day > currentDay)
                    {
                        currentDay = currentDay + 30;
                        currentMonth = currentMonth - 1;
                    }
                    if (month > currentMonth)
                    {
                        currentMonth = currentMonth + 12;
                        currentYear = currentYear - 1;
                    }
                    string agegrp;
                    var realAge = currentYear - year;
                    if (realAge < 18 && realAge > 13)
                    {
                        agegrp = "teen";
                        countteen++;
                    }
                    if (realAge < 26 && realAge > 18)
                    {
                        agegrp = "Young";
                        countYoung++;
                    }
                    if (realAge < 45 && realAge > 26)
                    {
                        agegrp = "Medioker";
                        countMedioker++;
                    }
                    else
                    {
                        agegrp = "Senior Citizen";
                        countSenior++;
                    }

                    ageVM.AgeGroupName = agegrp;


                    listAgeVM.Add(ageVM);
                }

                return listAgeVM;

            }


            public ActionResult AgeUserColumnChart()
            {
                ArrayList xValue = new ArrayList();
                ArrayList yValue = new ArrayList();
                var res = getuserAge();

                foreach (var item in res)
                {
                    xValue.Add(item.AgeGroupName);
                  //here yValue should come how to do that???
                }

                new Chart(width: 500, height: 300, theme: ChartTheme.Yellow)
                    .AddTitle("Age wise")
                    .AddSeries(chartType: "column", xValue: xValue,
                    yValues: yValue).Write("bmp");


                return null;
            }

вот моя ViewModel

public class AgeVM
    {
        public string AgeGroupName { get; set; }
        public int NoofUsers { get; set; }
    }

Пожалуйста, помогите мне спасти мой день.

1 Ответ

0 голосов
/ 07 мая 2018

Вы можете сделать функцию getuserAge() простой и понятной, используя словарь, определив AgeGroupName как ключ с четырьмя константами "teen", "Young" ...

итерация каждой записи и увеличение значения соответствующего ключа на единицу. В конце цикла вы получите ключ как AgeGroupName и значение как NoofUsers.

   public List<AgeVM> getuserAge()
        {
            List<AgeVM> listAgeVM = new List<AgeVM>();
            Dictionary<string, int> temp = new Dictionary<string, int>();
            temp.Add("teen", 0);
            temp.Add("Young", 0);
            temp.Add("Medioker", 0);
            temp.Add("Senior Citizen", 0);
            var res = from a in _Registrationrepository.GetAll()
                      select new
                      {
                          age = a.DOB,
                          name = a.FirstName,

                      };
            foreach (var item in res)
            {

                AgeVM ageVM = new AgeVM();
               //Write separate function to calculate age.                
                string agegrp;
                var realAge = currentYear - year;
                if (realAge < 18 && realAge > 13)
                {
                    temp["teen"]++;
                }
                if (realAge < 26 && realAge > 18)
                {
                    temp["Young"]++;
                }
                if (realAge < 45 && realAge > 26)
                {
                    temp["Medioker"]++;
                }
                else
                {
                    temp["Senior Citizen"]++;
                }
            }

  //Now outside foreach loop iterate through each key, value pair of dictionary and assing key to `AgeGroupName` and value to `NoofUsers` property

foreach(KeyValuePair<string, int> item in temp)
{

       ageVM.AgeGroupName = item.Key;
       ageVM.NoofUsers = item.Value;
}

            return listAgeVM;

        }

Это не весь код, но я дал вам идею. Как вы можете упростить свой код.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...