使用适当的值更新ProgressBar

4

由于我的数学能力有限,因此我面临的问题是:

我正在使用进度条来显示后台执行工作的进度:

以下是我的代码片段:

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

现在这个应用程序所做的远不止这些,而我只是完成了其中一小部分工作:

例如,在我到达这个部分之前,进度条的值为7,在执行工作后,它必须达到20,并且我希望在执行工作时使用适当的值从7更新它:

我的想法是:

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

非常感谢您的帮助:

非常感激您的协助:


这与答案无关 - 你确定你正确使用了动态吗? - Jason
是的,动态工作得很好,我拥有所有需要的值。 - Vasile Laur
2个回答

3

试试这个:

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

这里假设currentFriend的值从0开始一直到totalFriends-1为止。例如,如果currentFriend = 99,而totalFriends = 300,那么这个函数返回的答案是12。也就是说,位于8到20范围内(包含8和20)的区间已经过了三分之一。请注意保留html标记。

根据原始问题,这会导致一个偏移一的错误,因为currentFriend从1开始,而不是0。此外,如果像您建议的那样,currentFriend从0开始,第一个值应该是initVal,但是此函数返回initVal+1 - Adam Liss
@AdamLiss,目前的朋友从1开始并不清楚。我假设范围与C#数组中的索引相同,并在答案中提到了它。我还根据OP代码中的评论,在答案中添加了1个答案:“这将是计算的结果,一个值从8到20”。 - Sergey Kalinichenko
第一段代码将 i 设置为 0,然后在 foreach 循环的顶部对其进行递增。这意味着第一次调用 CalculatedValue 时,i 的值为 1。 - Adam Liss
@AdamLiss OP在循环中没有使用i,因此我会非常怀疑暗示currentFriend从1开始。无论如何,这是一个微不足道的问题,因为该公式中的1就在那里。 - Sergey Kalinichenko
两个答案都是正确的,将其设置为接受的答案仅为完整实现。 - Vasile Laur

3
您可以使用这个公式。
progressBarVal = initVal + (finalVal - initVal) * (currentFriend/totalFriends);

要检查数学计算,请在currentFriend为0时计算progressBarVal

initVal + (finalVal - initVal) * 0 = initVal

currentFriendtotalFriends 时:

initVal + (finalVal - initVal) * 1 = finalVal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接