1
我有數據,看起來像這些,例如:如何將數據庫錶轉換爲「數據透視表」DataTable?
| MemberID | Username | QuestionID | Question | Answer |
|----------|----------|------------|------------------|--------|
| 58 | John | 1 | Recommend This? | Yes |
| 58 | John | 2 | How much rating? | 10 |
| 59 | Zess | 1 | Recommend This? | No |
| 59 | Zess | 2 | How much rating? | 8 |
有這樣一個類(請忽略某些字段):
class reportlist
{
public string MemberID { get; set; }
public string Username { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int QuestionID { get; set; }
public string Question { get; set; }
public string Answer { get; set; }
public DateTime Submitted_On { get; set; }
public int TotalPoint { get; set; }
}
而且有一個MySQL的讀者將數據添加到reportlist:
while (reader.Read())
{
reportlist.Add(new reportlist() { MemberID = reader["MemberID"].ToString(), Username = reader["Username"].ToString(),
Name = reader["Name"].ToString(), Email = reader["Email"].ToString(), QuestionID = int.Parse(reader["QuestionID"].ToString()), Question = reader["Question"].ToString(),
Answer = reader["Answer"].ToString(), Submitted_On = DateTime.Parse(reader["CreationDate"].ToString()), TotalPoint = int.Parse(reader["TotalPoint"].ToString()) });
}
現在是我在哪裏卡住了,我嘗試使用LINQ查詢:
var groupedList = reportlist
.GroupBy(u => u.QuestionID, u => u.MemberID)
.ToList();
DataTable dt = new DataTable();
foreach (var group in groupedList)
{
//add columns, rows to datatable, stuck here
}
並不確定如何獲得這些結果到數據表中。基本上,我想團補的問題,並讓它成爲列,而所有的數據添加到數據表中形成這些結果(例如):
| MemberID | Username | Recommend This? | How much rating? |
| 58 | John | Yes | 10 |
| 59 | Zess | No | 8 |
請指導如何獲得的結果或更好的解決方案?由於我在linq中不擅長,所以我被困了一段時間。我確實嘗試過四處搜尋,產生的結果不多,也許不太明白它是如何工作的。
側信息:最終的數據表用於EPPlus庫(生成Excel電子表格)
欣賞你的解釋和代碼。謝謝! 已經通過它並能夠解決我的問題。絕對會研究它,並將其應用於即將開展的工作〜 – erkeni