2015-05-10 165 views
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電子表格)

回答

1

顯然,你在你的問題發佈的代碼不能成爲你真正的代碼,因爲它提供了以下,永遠不會編譯:

class reportlist { ... } 
reportlist.Add(new reportlist() { ... }); 

使一些假設要能夠回答這樣的問題:

List<reportlist> list; // the list filled by the data reader. 

你可以做一個「數據透視表」(即轉換行值列)在幾個步驟:

// Get unique question info. 
var questions = list 
    .GroupBy(x => x.QuestionID) 
    .Select(x => new { Id = x.Key, Title = x.First().Question }); 

// Set up the columns for the data table as a "pivot table" with columns per question. 
DataTable myTable = new DataTable("QuestionsPivotTable"); 
var fixedColumns = new [] { 
    new DataColumn("Member ID", typeof(string)), 
    new DataColumn("User Name", typeof(string)), 
}; 
var questionColumns = questions.Select(x => new DataColumn(x.Title, typeof(string))); 
myTable.Columns.AddRange(fixedColumns.Concat(questionColumns).ToArray()); 

隨着數據表的設置包括「樞軸」的問題列,我們可以得到用於每個部件上的行作爲值的數組:

// Get the column values for each member as an array. 
var rows = list 
    .GroupBy(x => x.MemberID) 
    .Select(x => { 
     var memberCols = new object[] { x.Key, x.First().Username }; 
     var answerCols = questions.Select(q => x.Where(a => a.QuestionID == q.Id).Select(a => a.Answer).FirstOrDefault()); 
     return memberCols.Concat(answerCols).ToArray(); 
    }); 

現在很容易填寫的表格:

// Fill the table. 
foreach (var memberRow in rows) 
{ 
    var row = myTable.NewRow().ItemArray = memberRow; 
    myTable.Rows.Add(row); 
} 

在哪裏,使用您的數據。例如,下面的代碼:

// Show the output 
for (var i = 0; i < myTable.Columns.Count - 1; i++) 
    Console.Write("{0}, ", myTable.Columns[i]); 
Console.WriteLine("{0}", myTable.Columns[myTable.Columns.Count - 1]); 
foreach (var row in myTable.AsEnumerable()) 
    Console.WriteLine(string.Join(", ", row.ItemArray.Select(x => x == null ? "<null>" : x.ToString()))); 

產生這樣的輸出:

Member ID, User Name, Recommend This?, How much rating? 
58, John, Yes, 10 
59, Zess, No, 8 
+0

欣賞你的解釋和代碼。謝謝! 已經通過它並能夠解決我的問題。絕對會研究它,並將其應用於即將開展的工作〜 – erkeni

相關問題