【发布时间】:2016-02-04 16:09:15
【问题描述】:
我有一个List 类型的元素
public class AnswerInfo
{
public string SectionTitle { get; set; }
public string SubsectionTitle { get; set; }
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int? AnswerId { get; set; }
public int? AnswerVal { get; set; }
}
当我检索它时,它将对应于从数据库中检索行,例如
-- =========================================================================================================================
-- section_title | subsection_title | question_id | question_text | answer_id | answer_val
-- =========================================================================================================================
-- 'Partner Planning' | 'Target Markets' | 1 | 'Have you defined the target ...?' | 1 | 24
-- 'Partner Planning' | 'Target Markets' | 2 | 'Have you identified the .......?' | 2 | 50
-- 'Partner Planning' | 'Target Markets' | 3 | 'Have you built a market .......?' | 3 | 90
-- 'Partner Planning' | 'Target Markets' | 4 | 'Have you built the revenue ....?' | NULL | NULL
-- 'Partner Planning' | 'Target Customers' | 5 | 'Have you defined the ideal ....?' | NULL | NULL
-- . . . . . .
-- . . . . . .
-- . . . . . .
-- . . . . . .
-- 'Partner Growth' | 'Getting Traction' | 61 | 'Have you defined the ideal ....?' | NULL | NULL
我通过存储过程来检索它
CREATE PROCEDURE GetAnswersByPartner
@pid UNIQUEIDENTIFIER -- Partner id
AS
BEGIN
SELECT Sections.title AS section_title,
Subsections.title AS subsection_title,
Questions.id AS question_id,
Questions.qtext AS question_text,
Answers.id AS answer_id,
Answers.val AS answer_val
FROM Partners
INNER JOIN Questions ON 1 = 1
INNER JOIN Subsections ON Subsections.Id = Questions.subsection_id
INNER JOIN Sections ON Sections.Id = Subsections.section_id
LEFT JOIN Answers ON Answers.partner_id = Partners.Id
AND Answers.question_id = Questions.Id
WHERE Partners.Id = @pid
END
在 C# 方面,
List<AnswerInfo> Answers = new List<AnswerInfo>();
using ( SqlCommand cmd = new SqlCommand("GetAnswersByPartner", this._Conn) )
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@pid", pid);
this._Conn.Open();
using ( SqlDataReader dataReader = cmd.ExecuteReader() )
{
while ( dataReader.Read() )
{
Answers.Add(
new AnswerInfo
{
SectionTitle = dataReader.GetString(0),
SubsectionTitle = dataReader.GetString(1),
QuestionId = dataReader.GetInt32(2),
QuestionText = dataReader.GetString(3),
AnswerId = dataReader.GetInt32(4),
AnswerVal = dataReader.GetInt32(5)
}
);
}
}
this._Conn.Close();
}
现在的问题是,为了构建我的视图,我希望能够像 List<AnswerInfo> 一样迭代
[伪代码]
for each section title
for each subsection title
for each { question id, question text, answer id, answer val }
我怎样才能以这种方式重新调整我的List<AnswerInfo>?更好的是,我可以预先创建所需的数据结构,然后在我遍历每个结果行时直接将标题添加到其中
while ( dataReader.Read() )
{
// Add info to better-organized structure
}
【问题讨论】:
标签: c# asp.net asp.net-mvc tsql data-structures