C# 地图列表<;列表<;字符串>&燃气轮机;进入列表<;字典<;字符串,int>&燃气轮机;

C# 地图列表<;列表<;字符串>&燃气轮机;进入列表<;字典<;字符串,int>&燃气轮机;,c#,c#-4.0,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

我正在尝试使用下面的代码将列表映射到字典列表中,但出现了错误

索引超出范围

更新问题

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 ++;            
}
List_terms=newlist();
对于(int i=0;i<\u numcats;++i)
{
_添加(生成表(_docs[i]);
}
//其中_docs[i]是一个数组元素
//和GenerateTerms返回列表的过程
int j=0;
foreach(列出术语中的术语)
{
对于(int i=0;i

有什么可以帮忙的吗?

我想,\u wordsIndex是
列表中的
。如果是这样,您可能正在尝试访问尚未添加的项目。因此,您需要将其更改为以下内容:

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)
}
foreach(列出术语)
{
var newDict=新字典();
对于(int i=0;i
请注意,字典在内部循环之前创建,在内部循环中填充,然后在内部循环结束后添加到主列表中。

  • \u术语
    是类型
    列表
  • \u wordsIndex
    是类型
    列表
试试这个:

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();
var\u wordsIndex=
_terms.Select(listOfWords=>
//对于每个单词列表
词表
//每个单词=>一对(单词,索引)
.选择((单词,单词索引)=>
新的KeyValuePair(字、字索引))
//把这些编入词典
.ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value))
//最后,列出结果字典
.ToList();

但是需要注意的是,这个错误也存在于示例代码中:在已经存在该键的字典上调用
Add
是不允许的。为了确保安全,您可能希望在键值对上获得一个
Distinct()

很可能
\u wordsIndex[j]
不可用。您能在初始化
\u wordsIndex
的地方共享您的代码吗?@Sinngh。。我已经更新了问题,我确信列表是正确的available@Qaesar-这就是你初始化术语的地方,但是问题可能就在这里,@Sinngh.第一个循环工作得很好,我得到了一个由项目填充的列表。但是第二个循环给出了所提到的error@Qaesar显式循环是不必要的。见下面的杰金鲍尔和我的答案。KVP位很聪明,我应该想到这一点+1Hah-看起来你比我快了一分钟;没有注意到“发布新答案”的横幅。:)