2016-06-12 3 views
-1

я должен заполнить в некоторых списках в то время как цикл, как:Чтение в списке с помощью SqlDataReader C#

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 графа должны = 1.

enter image description here

Изображение 2: Отображение отдельных списков атрибутов для каждой строки, как и в третьей итерации, атрибут eg CoAuthorID, граф = 1, в то время как оно должно быть = 3, а в 3-й итерации и то же самое для остальной части Attributes

enter image description here

+0

У этого есть серьезные проблемы. Как вы узнаете, с какими документами связан CoAuthor_ID 1695352. Или когда год переместился на 2007 год. Вам нужна более формальная структура данных. – Paparazzi

+0

Мне нужно отследить авторов и их атрибуты, т. Е. Документ, CoAuthor и место проведения в соответствующие годы, не желательно здесь, какая бумага CoAuthor_ID 1695352 связана с – maliks

+0

Ну, вы даже не получаете * соответствующие * Годы здесь. Почему новый автор не инициализирует этот список? Выглядит неряшливо для меня. – Paparazzi

ответ

1

Следуя структуре данных, показанной и видя, что изображено на изображениях, кажется, что все att (Paper, CoAuthor, Venue) являются списками типов, поэтому нет необходимости объявлять атрибуты как List<AuthorAttributes>. Следуйте за этим к тому, что вы хотите достичь:

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 AuthorAttributes() 
     }; 
    } 

    // Check if list _PaperID doesn't exist 
    if (_author._Attributes._PaperID == null) 
    { 
     // Create new _PaperID 
     _author._Attributes._PaperID = new List<int>(); 
     // Add Paper_ID to _PaperID 
     _author._Attributes._PaperID.Add(_myReader_1.GetInt32(2)); 
    } 
    else // Add Paper_ID to existing _PaperID list 
    _author._Attributes._PaperID.Add(_myReader_1.GetInt32(2)); 

    // Check if list _CoAuthorID doesn't exist 
    if (_author._Attributes._CoAuthorID == null)  
    { 
     // Create new _CoAuthorID 
     _author._Attributes._CoAuthorID = new List<int>(); 
     // Add CoAuthor_ID to _CoAuthorID 
     _author._Attributes._CoAuthorID.Add(_myReader_1.GetInt32(3)); 
    } 
    else // Add CoAuthor_ID to existing _CoAuthorID list 
    _author._Attributes._CoAuthorID.Add(_myReader_1.GetInt32(3)); 

    // Check if list _CoAuthorID doesn't exist 
    if (_author._Attributes._VenueID == null)  
    { 
     // Create new _VenueID 
     _author._Attributes._VenueID = new List<int>(); 
     // Add Venue_ID to _VenueID 
     _author._Attributes._VenueID.Add(_myReader_1.GetInt32(4)); 
    } 
    else // Add Venue_ID to existing _VenueID list 
    _author._Attributes._VenueID.Add(_myReader_1.GetInt32(4)); 

    // Add Year to _Year 
    _author._Attributes._Year =_myReader_1.GetInt32(5); 

    if (!_eAthors.Contains(_author)) 
    _eAthors.Add(_author); 
} 
_myReader_1.Close(); 
+1

Он выглядит более красивым, хотя каждый атрибут обрабатывается отдельно! – maliks

+0

Вам не нужно повторять все эти .Add. – Paparazzi

+0

Затем как добавить в каждый список атрибутов отдельно? – maliks

1

Если предположить, что структура данных выглядит следующим образом:

Author 
    AuthorAttributes 
     Papers (list) 
      PaperID 
     CoAuthors (list) 
      CoAuthorID 
     Venues (list) 
      VenueID 
     Year 

Вы могли бы попробуйте следующее:

while (_myReader_1.Read()) 
{ 
    _Row_Counter++; 

    int _authorID = _myReader_1.GetInt32(0); 
    string _authorName = _myReader_1.GetString(1); 
    int _paperID = _myReader_1.GetInt32(2); 
    int _coAuthorID = _myReader_1.GetInt32(3); 
    int _venueID = _myReader_1.GetInt32(4); 
    int _year = _myReader_1.GetInt32(5); 

    Author _author = _eAthors.FirstOrDefault(_a => _a._AuthorID == _authorID); 
    if (_author == null) 
    { 
     _author = new Author 
     { 
      _AuthorID = _authorID, 
      _AuthorName = _authorName, 
      _AuthorAttributes = new AuthorAttributes 
      { 
       _Papers = new List<int>(), 
       _Venues = new List<int>(), 
       _Year = _year, 
       _CoAuthors = new List<int>() 
      } 
     }; 
     _eAthors.Add(_author); // only add if author not found 
    } 

    if (!_author._AuthorAttributes._Papers.Contains(_paperID)) 
     _author._AuthorAttributes._Papers.Add(_paperID); 
    if (!_author._AuthorAttributes._CoAuthors.Contains(_coAuthorID)) 
     _author._AuthorAttributes._CoAuthors.Add(_coAuthorID); 
    if (!_author._AuthorAttributes._Venues.Contains(_venueID)) 
     _author._AuthorAttributes._Venues.Add(_venueID); 
} 
_myReader_1.Close(); 
+0

«Идентификатор объекта» также есть список, и у меня нет класса «Бумага», вместо этого у меня есть класс 'AuthorAttributes' – maliks

+0

Хорошо, отредактируйте, чтобы отразить это –

+1

Еще одно! 'PaperID' также является списком, поскольку' Author_ID' имеет много 'Paper_ID' – maliks

-1

Добавить вновь созданный автором сразу после инициализации в author == null проверки. Затем проверьте, есть ли author.PaperID == null, и если да, добавьте AuthorAttributes. Как это:

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>() 
     }; 

     _eAthors.Add(_author); // ********** Add the new author 
    } 

    // Watch out!!! author.Attributes may be null for existing authors!!! 
    if (author.Attributes.PaperID == null || author.PaperID.Count == 0) // Check for PaperID existence 
    { 
     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); 
    } 
} 
_myReader_1.Close(); 

Конечно, при необходимости можно обработать каждый атрибут отдельно, добавляя if блок для каждого из них.

Смежные вопросы