【发布时间】:2016-10-12 20:41:02
【问题描述】:
我必须在while循环中填写一些列表:
while (_myReader_1.Read())
{
_Row_Counter++;
int _authorID = _myReader_1.GetInt32(0);
Author _author = _eAthors.FirstOrDefault(_a => _a._AuthorID == _authorID);
if (_author == null)
{
_author = new Author
{
_AuthorID = _authorID,
_AuthorName = _myReader_1.GetString(1),
_Attributes = new List<AuthorAttributes>()
};
}
var _attribute = new AuthorAttributes()
{
_PaperID = new List<int>(),
_CoAuthorID = new List<int>(),
_VenueID = new List<int>()
};
_attribute._PaperID.Add(_myReader_1.GetInt32(2));
_attribute._CoAuthorID.Add(_myReader_1.GetInt32(3));
_attribute._VenueID.Add(_myReader_1.GetInt32(4));
_attribute._Year = _myReader_1.GetInt32(5);
_author._Attributes.Add(_attribute);
_eAthors.Add(_author);
}
_myReader_1.Close();
SQL表中的数据如下:
Author_ID | Author_Name | Paper_ID | CoAuthor_ID | Venue_ID | Year
------------------------------------------------------------------
677 | Nuno Vas | 812229 | 901706 | 64309 | 2005
677 | Nuno Vas | 812486 | 901706 | 65182 | 2005
677 | Nuno Vas | 818273 | 901706 | 185787 | 2005
677 | Nuno Vas | 975105 | 901706 | 113930 | 2007
677 | Nuno Vas | 975105 | 1695352 | 113930 | 2007
... | ... | ... | ... | ... | ...
问题是每次循环迭代时,都会创建新列表 _PaperID、_CoAuthorID 和 _VenueID,这是不需要的。因为我们有一个检查if(author == null),所以要创建一个新作者,同样我想检查一个作者是否存在_PaperID 的列表,例如对于Author_ID = 677,然后在同一列表中添加,直到Author_ID 被更改。
同样直到Author_ID = 677,列表_eAuthors 应该有Count = 1
我附上了一些图片来完善问题。
图片 1: 显示 eAuthors Count = 3,Attributes Count = 3,AuthorID = 677,而 3 次迭代通过,而 eAuthors Count 应该 = 1。
图片 2: 显示每行的单个属性列表,如第三次迭代中的属性,例如CoAuthorID,Count = 1,而在第 3 次迭代中它应该是 = 3,其余的 Attributes 也是一样的
【问题讨论】:
-
这有严重的问题。你怎么知道 CoAuthor_ID 1695352 与哪篇论文相关联。或者当年份移到 2007 年时。您需要一个更正式的数据结构。
-
我需要跟踪作者及其属性,即各自年份的论文、共同作者和地点,此处不需要 CoAuthor_ID 1695352 与哪篇论文相关
-
嗯,你甚至没有得到各自的年。为什么新作者没有初始化这些列表?在我看来很草率。
-
如果您只想了解作者发表的所有独特论文、合著者、地点和年份,而不考虑它们之间的关系,那么年份也应该在列表中。如果它们需要关联,那么您需要一个具有 PaperID、共同作者列表、交付它的地点 ID 和出版年份的类 Paper。然后,您将获得一份 Paper 项目列表。
-
@JohnD 你的观点很好,但是如果我们有一个
Paper作为一个类,你的回答代码会保持不变吗?我们仍然应该有每个作者的论文、共同作者和地点的列表......这个呢?
标签: c# list while-loop sqldatareader