Home > database >  C# : Creating Nested dictionary using for loop
C# : Creating Nested dictionary using for loop

Time:08-02

I have declared 2 dictionaries as below for collecting number of annotations in each page of a PDF.

 Dictionary<string, int> tempDict = new Dictionary<string, int>();
 Dictionary<int, Dictionary<string, int>> masterDict = new Dictionary<int, Dictionary<string, int>>();

The output am looking for is such that the tempdict will hold the annotation name as 'Key' and annotation-index as 'Value' and masterDict will hold pagenumber as 'Key' and tempDict as the 'Value'

Below is what I tried :

pDDoc = (CAcroPDDoc)avDoc.GetPDDoc();
int numPages = pDDoc.GetNumPages(); //Gets total number of pages in the PDF
            
for (int i = 0; i < numPages; i  )
    {
    pDPage = (CAcroPDPage)pDDoc.AcquirePage(i); //Gets the page object corresponding to pagenumber
    long y = pDPage.GetNumAnnots(); //Gets the number of annots in the acquired page
    
    for (int j = 0; j < y; j  )
        {
         pDAnnot = (CAcroPDAnnot)pDPage.GetAnnot(j); //Gets annot object at the 'j' index position
         string name = pDAnnot.GetTitle();
         tempDict.Add(name , j); // Name, index as Key,value
        }
    masterDict.Add(i, tempDict); // Pagenum, tempDict as Key,Value
    }
                

The above code works, but it is not the result I was expecting .If there are 10 annotations in a PDF having 2 pages, Page1 having 6 annots and Page2 having 4 annots, masterDict will look like this :

{[0,Count = 10]}
{[1,COunt = 10]}

What I want is it to look like this:

{[0,Count = 6]}
{[1,Count = 4]}
               

How can I achieve this ? Is Add() method the right approach?

CodePudding user response:

You're only creating one instance of tempDict. You need to create a new one each loop.

Try this:

pDDoc = (CAcroPDDoc)avDoc.GetPDDoc();
int numPages = pDDoc.GetNumPages(); //Gets total number of pages in the PDF

for (int i = 0; i < numPages; i  )
{
    pDPage = (CAcroPDPage)pDDoc.AcquirePage(i); //Gets the page object corresponding to pagenumber
    long y = pDPage.GetNumAnnots(); //Gets the number of annots in the acquired page
    var tempDict = new Dictionary<string, int>();
    for (int j = 0; j < y; j  )
    {
        pDAnnot = (CAcroPDAnnot)pDPage.GetAnnot(j); //Gets annot object at the 'j' index position
        string name = pDAnnot.GetTitle();
        tempDict.Add(name, j); // Name, index as Key,value
    }
    masterDict.Add(i, tempDict); // Pagenum, tempDict as Key,Value
}
  • Related