Exemple #1
0
        private void BtnDivide_Click(object sender, RoutedEventArgs e)
        {
            if (!_peopleList.Any())
            {
                MessageBox.Show("Lägg till en person eller två först!");
                return;
            }
            if (string.IsNullOrEmpty(TxtBoxCandyAmount.Text) ||
                !int.TryParse(TxtBoxCandyAmount.Text, out int candies))
            {
                MessageBox.Show("Mata in hur många godisar du vill fördela!");
                return;
            }

            DivideCandyMethod divideMethod = DivideCandyMethod.ByOrder;

            if (RadioBtnByAge.IsChecked.Value)
            {
                divideMethod = DivideCandyMethod.ByAge;
            }
            else if (RadioBtnByName.IsChecked.Value)
            {
                divideMethod = DivideCandyMethod.ByName;
            }

            _calculator.NumberOfCandies = candies;
            _calculator.DivideCandy(divideMethod);
            ListBoxPersons.Items.Refresh();
        }
        public void DivideCandy(DivideCandyMethod method = DivideCandyMethod.ByOrder)
        {
            int candiesPerPerson = NumberOfCandies / people.Count;
            int rest             = NumberOfCandies % people.Count;

            foreach (var p in people)
            {
                p.Candies = candiesPerPerson;
            }

            IEnumerable <Person> toGiveExtraCandies = null;

            if (method == DivideCandyMethod.ByOrder)
            {
                toGiveExtraCandies = people.Take(rest);
            }
            else if (method == DivideCandyMethod.ByAge)
            {
                toGiveExtraCandies = people.OrderBy(o => o.Age).Take(rest);
            }
            else
            {
                toGiveExtraCandies = people.OrderBy(o => o.Firstname).Take(rest);
            }

            foreach (var p in toGiveExtraCandies)
            {
                p.Candies++;
            }
        }