【问题标题】:Using cross-join / pivot with Linq在 Linq 中使用交叉连接/透视
【发布时间】:2017-01-26 05:42:46
【问题描述】:

我有一个具有以下结构的集合。

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 个问题。我相信我需要自行交叉加入集合,并以某种方式将问题显示为标题(枢轴行和列)。我无法生成目标数据格式。任何帮助表示赞赏。

【问题讨论】:

    标签: c# linq pivot cartesian-product


    【解决方案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; }
        }
    }
    

    提供以下内容:

    【讨论】:

    • 感谢您提供此解决方案。虽然它没有按描述输出数据,但它提供了很好的洞察力,因此值得一票。
    • 输入没有映射到你的输出,所以我尽我所能。
    猜你喜欢
    • 2014-03-08
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 2014-03-17
    • 2013-05-24
    • 2016-11-11
    相关资源
    最近更新 更多