簡體   English   中英

地圖列表 <List<string> &gt;進入清單 <Dictionary<string, int> &gt;

[英]Map List<List<string>> into List<Dictionary<string, int>>

我正在嘗試以下代碼將列表列表映射到字典列表但我收到錯誤

指數超出范圍

更新了問題

List<List<string>> _terms = new List<List<string>>();
for (int i = 0; i < _numcats; ++i)
{
    _terms.Add( GenerateTerms(_docs[i]));
}
// where _docs[i] is an array element 
// and the procedure GenerateTerms returns list  

int j = 0;
foreach (List <string> catterms in _terms)
{
    for (int i = 0; i < catterms.Count; i++)
    {
        _wordsIndex[j].Add(catterms[i], i);
    }
    j ++;            
}

請問有什么幫助嗎?

假設:

  • _terms是類型List<List<string>>
  • _wordsIndex的類型為List<Dictionary<string,int>>

嘗試這個:

var _wordsIndex = 
    _terms.Select(listOfWords => 
        // for each list of words
        listOfWords
            // each word => pair of (word, index)
            .Select((word, wordIndex) => 
                   new KeyValuePair<string,int>(word, wordIndex))
            // to dictionary these
            .ToDictionary(kvp => kvp.Key, kvp => kvp.Value))
        // Finally, ToList the resulting dictionaries
        .ToList();

但請注意 - 此示例代碼中也存在此錯誤:在已存在該密鑰的字典上調用Add是禁止的。 為確保此處的安全性,您可能希望在鍵值對上獲得Distinct()

我假設_wordsIndex是List<Dictionary<string, int>> 如果是這樣,您可能正在嘗試訪問尚未添加的項目。 所以你需要把它改成這樣的東西:

foreach (List <string> catterms in _terms)
{
    var newDict = new Dictionary<string, int>();
    for (int i = 0; i < catterms.Count; i++)
    {
        newDict.Add(catterms[i], i);
    }
    _wordsIndex.Add(newDict)
}

請注意,在內部循環之前創建字典,在內部循環中填充,然后在內部循環結束后添加到主列表。

暫無
暫無

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

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