将列表<列表<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>>
  • _wordsIndexList<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)
}

请注意,字典是在内部循环之前创建的,在内部循环中填充,然后在内部循环结束后添加到主列表中。

最新更新