簡體   English   中英

C#:使用 for 循環創建嵌套字典

[英]C# : Creating Nested dictionary using for loop

我已經聲明了如下 2 個字典,用於收集 PDF 的每一頁中的注釋數量。

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

我正在尋找的 output 是這樣的,即 tempdict 將注解名稱保存為“Key”,注解索引保存為“Value”,masterDict 將頁碼保存為“Key”,tempDict 保存為“Value”

以下是我嘗試過的:

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
    }
                

上面的代碼有效,但這不是我期望的結果。如果 PDF 中有 10 個注釋,有 2 個頁面,Page1 有 6 個注釋,Page2 有 4 個注釋,masterDict 將如下所示:

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

我想要的是它看起來像這樣:

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

我怎樣才能做到這一點? Add() 方法是正確的方法嗎?

您只創建了一個tempDict實例。 您需要在每個循環中創建一個新的。

嘗試這個:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM