我正在创建一个cusstomer进度对话框,用于跟踪已将多少对象上传到Web服务。过程如下:
如何根据分成20个块的x长度数组计算每个块的单个百分比,最高可达100%。
答案 0 :(得分:1)
// preparation
var chunkCount = (TotalItemCount - (TotalItemCount % 20)) / 20 + (TotalItemCount % 20 > 0 ? 1 : 0);
var percentage = 0.00d;
// progress
var chunkSize = ... // 20 or less for the last
var currentChunkIndex = ...
percentage += (chunkSize + (currentChunkIndex * 20)) / TotalItemCount;
此计算将确保最后一个块的百分比也正确。
答案 1 :(得分:0)
len - length of the list
chunk_size = 20 - chunk size
chunk_count - number of chunks
individual_percentage - what percentage of all chunks is one chunk
last_percentage - what percentage of all chunks is the last chunk
which might be smaller than 20
chunk_count = len / chunk_size
chunk_count = len / 20
individual_percentage = 100 / chunk_count
last_percentage = 100 - (individual_percentage * (chunk_count - 1))
答案 2 :(得分:0)
首先,如果总大小为n
,您需要找出20的百分比。要获得该值,您需要计算
unitSize = 100 * (20 / n);
现在,如果您有一个以前的百分比,那么在完成一个20块之后,请更新它:
previousPercentage += unitSize;
其中previousPercentage
将初始化为0。
答案 3 :(得分:0)
有两种可能的解决方案:
计算已完成的块的进度
int count;
int processed;
int progress;
var collection = Enumerable.Range(1, 111).ToList();
var chunks = collection.Partition(20).ToList();
Console.WriteLine("Process chunks (Progress from chunks)");
count = chunks.Count;
processed = 0;
foreach (var item in chunks)
{
// do some actions with the chunk
processed++;
progress = processed * 100 / count;
Console.WriteLine(progress);
}
生成输出:
Process chunks (Progress from chunks) 16 33 50 66 83 100
计算已完成项目的进度
int count;
int processed;
int progress;
var collection = Enumerable.Range(1, 111).ToList();
var chunks = collection.Partition(20).ToList();
Console.WriteLine("Process chunks (Progress from chunk.Count)");
count = collection.Count;
processed = 0;
foreach (var item in chunks)
{
// do some actions with the chunk
processed += item.Count();
progress = processed * 100 / count;
Console.WriteLine(progress);
}
生成输出:
Process chunks (Progress from chunk.Count) 18 36 54 72 90 100
选择您最喜欢的
Partition
方法是自定义LINQ扩展
public static class EnumerableExtensions
{
public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> source, int partitionSize)
{
if (source == null)
throw new ArgumentNullException("source");
if (partitionSize <= 0)
throw new ArgumentOutOfRangeException("partitionSize");
return source
.Select((e, i) => new { Part = i / partitionSize, Item = e })
.GroupBy(e => e.Part, e => e.Item);
}
}