2016-09-18 71 views
0

我有一個具有以下結構的集合。與Linq一起使用交叉連接/樞軸

List<QuestionAnswer> answers = new List<QuestionAnswer>(){}; 

class QuestionAnswer 
{ 
    string Question { get; set; } 
    string Answer { get; set; } 
} 

它填充了以下數據:

Question Answer 
Q1  a 
Q1  b 
Q2  c 
Q2  d 
Q2  e 

我需要將其轉換爲以下格式:

Q1 Q2 
a c 
a d 
a e 
b c 
b d 
b e 

的問題是不知道,直到運行時;收集中可能有n個問題。我相信我需要CROSS JOIN集合本身,並以某種方式顯示問題作爲標題(透視行和列)。我無法產生目標數據格式。任何幫助表示讚賞。

回答

1

你可以做這樣的事情

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<QuestionAnswer> answers = new List<QuestionAnswer>() { 
       new QuestionAnswer() { Question = "Q1", Answer = "a"}, 
       new QuestionAnswer() { Question = "Q1", Answer = "b"}, 
       new QuestionAnswer() { Question = "Q2", Answer = "c"}, 
       new QuestionAnswer() { Question = "Q2", Answer = "d"}, 
       new QuestionAnswer() { Question = "Q2", Answer = "e"}, 
      }; 

      DataTable dt = new DataTable(); 
      List<string> uniqueQuestions = answers.Select(x => x.Question).Distinct().ToList(); 

      foreach (string question in uniqueQuestions) 
      { 
       dt.Columns.Add(question, typeof(string)); 
      } 

      var groups = answers.GroupBy(x => x.Answer).ToList(); 

      foreach (var group in groups) 
      { 
       DataRow newRow = dt.Rows.Add(); 
       foreach (QuestionAnswer qA in group) 
       { 
        newRow[qA.Question] = qA.Answer; 
       } 
      } 

     } 
    } 
    public class QuestionAnswer 
    { 
     public string Question { get; set; } 
     public string Answer { get; set; } 
    } 
} 

,帶出以下幾點: enter image description here

+0

感謝你們提供了這個解決方案。雖然它沒有輸出所描述的數據,但它提供了一個很好的見解,因此值得投票。 – Thracian

+0

輸入沒有映射到您的輸出,所以我盡我所能。 – jdweng