Raz*_*t4x 0 c# sql generics .net-3.5 visual-studio-2008
好的,所以你从标题中得到了想法,让我发布代码并在评论中我会解释发生了什么(以及应该做什么!)
// 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);
}
Run Code Online (Sandbox Code Playgroud)
我猜我在代码注释中解释了所有内容,但如果您仍需要澄清任何内容,请随时提出.但基本上,就像我说的,当我到SomeMethod时,List似乎没有维护它的项目(如果超过11)(这是奇怪还是什么?)那么,有谁可以帮我这个?任何帮助,将不胜感激.
更新: 它不是存储了11个项目,它就是最后一个主题的类数量,这些项目的数量是存储的.假设在上部循环中,主题的最后一个id是52,并且对于该id有23个类,那么对于每个插入的记录,甚至在此之前,_clsSub值的列表将具有最多23个项目.
你宣布一次:
List<Int32> lstTempSub = new List<int>();
Run Code Online (Sandbox Code Playgroud)
由于它是一个引用类型,因此无论何时使用它,您实际上都在使用它的引用.所以当你在循环中执行此操作时:
_clsSub.Add(nTempID, lstTempSub);
Run Code Online (Sandbox Code Playgroud)
您将相同的列表添加到字典中的每个插槽.当你这样做:
lstTempSub.Clear();
Run Code Online (Sandbox Code Playgroud)
您正在清除字典中每个插槽中的相同列表.因此,字典中的所有列表都是相同的列表,并最终包含最后一个循环中的内容(即上次清除并添加到其中的内容).
你需要移动List<Int32> lstTempSub = new List<int>();到while循环代替行lstTempSub.Clear();,一切都会工作.
(回答你的标题问题,如果它不明显 - 你循环的最后一件事有11项,所以它们似乎都有11个项目因为它们指向同一个项目)
| 归档时间: |
|
| 查看次数: |
126 次 |
| 最近记录: |