Home > Software engineering >  Count percentage of more foreach loop
Count percentage of more foreach loop

Time:10-05

I am trying to implement a script that gets the 0-100 percentage of the iteration of more than 1 loop (in my specific case 3 loop):

I show you the Code Sample:

int progress = 0;
foreach (KeyValuePair<long, Dictionary<long, List<MyStruct>>> ad in allDocuments)
{
    Dictionary<long, List<MyStruct>> categoriesDocs = ad.Value;

    foreach (KeyValuePair<long, List<MyStruct>> categoryDocs in categoriesDocs)
    {
       List<MyStruct> docs = categoryDocs.Value;

       foreach(MyStruct doc in docs)
       {
           progress = ???

           //... CODE ....
       }
    }
}

How can I calculate progress value with correct percentage?

CodePudding user response:

Count up the total first, and then you can calculate the progress.

int total = 0;

foreach (KeyValuePair<long, Dictionary<long, List<MyStruct>>> ad in allDocuments)
{
    Dictionary<long, List<MyStruct>> categoriesDocs = ad.Value;

    foreach (KeyValuePair<long, List<MyStruct>> categoryDocs in categoriesDocs)
    {
       total  = categoryDocs.Value.Count;
    }
}

int progress = 0;

foreach (KeyValuePair<long, Dictionary<long, List<MyStruct>>> ad in allDocuments)
{
    Dictionary<long, List<MyStruct>> categoriesDocs = ad.Value;

    foreach (KeyValuePair<long, List<MyStruct>> categoryDocs in categoriesDocs)
    {
       List<MyStruct> docs = categoryDocs.Value;

       foreach(MyStruct doc in docs)
       {
           //... CODE ....
           
             progress;

           double percentComplete = (100.0 * progress)/total;
       }
    }
}

If you wanted to use Linq to calculate the total rather than writing an explicit loop, you could use:

int total = allDocuments
   .SelectMany(doc => doc.Value)
   .Sum(docList => docList.Value.Count);

(I've assumed that allDocuments is of type Dictionary<long, Dictionary<long, List<MyStruct>>>)

Note that this is no faster than the explicit loop, but some people may prefer it.

  •  Tags:  
  • c#
  • Related