2016-09-18 74 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