地图列表<list <string>&gt;到List <dictionary <string,int =“”>&gt; </dictionary <string,> </list <string>

时间:2012-11-28 19:55:51

标签: c# c#-4.0

我正在尝试以下代码将列表列表映射到字典列表但我收到错误

  

指数超出范围

更新了问题

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 ++;            
}

请问有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

假设:

  • _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()

答案 1 :(得分:1)

我假设_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)
}

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