vendredi 29 décembre 2017

Simplify chain of if statements in a foreach

I have this logic and it's working but it's not pretty (as I'm sure you can tell). There are rewards that are given when a person reaches a certain level and I need to show the date when the person reaches the reward. So if a person reaches the over 250 dollar reward show the date. But if a person spends $1000 in one day then I need to show that they have reached Level 1, 2, and 3 all on the same day. All the DateTimes are null to begin with. How could I simplify the if chain that I have going on:

foreach (var receipt in receiptsLastYear.OrderBy(x => x.DateCreated))
        {
            totalLastYear += receipt.Amount;
            if (totalLastYear >= 250 && totalLastYear < 500 && 
                vm.Rewards.DateAwardedLevel1 == null)
            {
                vm.Rewards.DateAwardedLevel1 = receipt.DateCreated;
            }
            if (totalLastYear >= 500 && totalLastYear < 1000 && 
                vm.Rewards.DateAwardedLevel2 == null)
            {
                if (vm.Rewards.DateAwardedLevel1 == null)
                {
                    vm.Rewards.DateAwardedLevel1 = receipt.DateCreated;
                }
                vm.Rewards.DateAwardedLevel2 = receipt.DateCreated;
            }
            if (totalLastYear >= 1000 && totalLastYear < 2500 && 
                vm.Rewards.DateAwardedLevel3 == null)
            {
                if (vm.Rewards.DateAwardedLevel1 == null)
                {
                    vm.Rewards.DateAwardedLevel1 = receipt.DateCreated;
                }
                if (vm.Rewards.DateAwardedLevel2 == null)
                {
                    vm.Rewards.DateAwardedLevel2 = receipt.DateCreated;
                }
                vm.Rewards.DateAwardedLevel3 = receipt.DateCreated;
            }
            if (totalLastYear >= 2500 && vm.Rewards.DateAwardedLevel4 == 
                 null)
            {
                if (vm.Rewards.DateAwardedLevel1 == null)
                {
                    vm.Rewards.DateAwardedLevel1 = receipt.DateCreated;
                }
                if (vm.Rewards.DateAwardedLevel2 == null)
                {
                    vm.Rewards.DateAwardedLevel2 = receipt.DateCreated;
                }
                if (vm.Rewards.DateAwardedLevel3 == null)
                {
                    vm.Rewards.DateAwardedLevel3 = receipt.DateCreated;
                }
                vm.Rewards.DateAwardedLevel4 = receipt.DateCreated;
            }
        }

Aucun commentaire:

Enregistrer un commentaire