Update ProgressBar with appropriate value

Math is not strong, so here is my problem:

I use a progress bar to show progress in the background:

Snippet of my code:

int i = 0; int totalFriends = 0; foreach (dynamic friend in facebookFriends) { totalFriends++; } foreach (dynamic friend in facebookFriends) { i++; var friend = new FacebookFriend { FbId = friend["uid"].ToString() }; AccountFacebookFriendRepository.SaveOrUpdate(accountFriend); } 

Now the application does much more than this, and here I am only doing a small piece of work: So, for example, before I got to this section, the progress bar had a value of 7 and after doing the work it should have reached 20, and I want update it by working with the corresponding values ​​from 7 to 20:

I accept the following:

 var intiProgressbarValue = 7; var finalProgressbarvalue = 20; foreach (dynamic friend in facebookFriends) { i++; var friend = new FacebookFriend { FbId = friend["uid"].ToString() }; AccountFacebookFriendRepository.SaveOrUpdate(accountFriend); var calculatedValue = CalculatedValue(initProgressbarValue, finalProgressBarValue,totalFriends, i); UpdateProgressBar( calculatedValue); } //note that totalFriends can be any number lets say from 0 to 5000 private int CalculatedValue(int initVal, int finalVal, int totalFriends, int currentFriend) { int progressBarVal = 0; //** Perform logic so it will return a progress value that is bigger that 7 and smaller that 20 depending on the number of friends and currently updated friend **// progressBarVal = 8;//this would be the result of calculation, a value from 8 to 20 return progressBarVal; } 

Any help is much appreciated:

+4
source share
2 answers

Try the following:

 private int CalculatedValue(int initVal, int finalVal, int totalFriends, int currentFriend) { initVal++; var diff = finalVal - initVal; // 20-8 = 12 return (diff*(currentFriend+1))/totalFriends + initVal; } 

This assumes that currentFriend changes from 0 to totalFriends-1 inclusive. For example, if currentFriend = 99 and totalFriends = 300 , the answer that this function returns is 12, one third is in the range of 8..20 (inclusive).

+3
source

You can use the formula

 progressBarVal = initVal + (finalVal - initVal) * (currentFriend/totalFriends); 

To check the math, calculate progressBarVal when currentFriend is 0:

 initVal + (finalVal - initVal) * 0 = initVal 

and when currentFriend totalFriends :

 initVal + (finalVal - initVal) * 1 = finalVal 
+3
source

Source: https://habr.com/ru/post/1398434/


All Articles