好的,所以您从标题中得到了想法,让我发布代码并在评论中解释正在发生的事情(以及应该发生的事情!)
// select distinct subject from database
cmd.CommandText = "SELECT DISTINCT SubjectId FROM ClassSubject";
// a new command
OleDbCommand cmdTemp = new OleDbCommand();
// con id defined earlier
cmdTemp.Connection = con;
// Reader for outer loop
OleDbDataReader rdr;
// reader for inner loop
OleDbDataReader rdrTemp;
// reader for main command, that is for each subject
rdr = cmd.ExecuteReader();
// this will store subject id
int nTempID;
// this is the list that is supposed to contain all the classes (many to many relation btw class and subject)
// it does gets set fine, but later only 11 items show up
List<Int32> lstTempSub = new List<int>();
// a dictionary that will store all classes for this each particular subject
_clsSub = new Dictionary<int, List<int>>();
// read main, i.e. read subjects
while (rdr.Read())
{
// set the id of subject
nTempID = rdr.GetInt32(0);
// clear previous items
lstTempSub.Clear();
// this selects all the classes for this particular subject
cmdTemp.CommandText = "SELECT ClassId FROM ClassSubject WHERE SubjectID=" + nTempID + " ORDER BY ClassID";
// Execute in the tempReader
rdrTemp = cmdTemp.ExecuteReader();
// read
while (rdrTemp.Read())
{
// here, we add all the classes that are there for this particular subject to the list we createed
lstTempSub.Add(rdrTemp.GetInt32(0));
}
// close inner one
rdrTemp.Close();
// every thing is fine till here,
// i.e. nTempId is what is should be, the id of this particular subect
// lstTempSub contains all class for this subject, may be 1 or may be 100
_clsSub.Add(nTempID, lstTempSub);
}
// close outer one
rdr.Close();
// Here is where things get wrong
foreach(KeyValuePair<Int32, List<Int32>> pair in _clsSub)
{
// when the debugger gets here, the key is fine for each subject
// but pair.Value always have 11 values at most, if for a subject
// there were less class, then it shows okay,
// but in case there were more than 11, only 11 values are shown in pair.value
SomeMethod(pair.Key, pair.Value);
}
我想我在代码注释中解释了所有内容,但如果您仍然需要澄清任何内容,请随时提问。但基本上,就像我说的,当我到达 SomeMethod 时,列表似乎没有维护它的项目(如果超过 11 个)(这是奇怪的还是什么?)那么,有人可以帮我解决这个问题吗?任何帮助,将不胜感激。
更新: 不是存储了 11 个项目,而是无论最后一个主题的课程数量是多少,存储的项目数量都是如此。假设在上层循环中,主题的最后一个 id 是 52,并且该 id 有 23 个类,那么对于插入的每条记录,甚至在之前,_clsSub
值的列表将最多有 23 个项目。