c# - 自然加入.net

标签 c# linq join pivot-table

我正在尝试从 2 个表在 Linq 中进行自然左连接

2 个表

| questions |
+-----------+
| id        |
| question  |
+-----------+


|  answers  |
+-----------+
|  id       |
|  q_id (fk)|
|  answer   |
+-----------+

我试图为每个问题检索一行,但根据需要使用尽可能多的额外列

我不确定这是否可能

                      ID   | Question   | Answer 1 | Answer 2 | An....
| view      |       |-----------------------------------------------+
+-----------+       |  1   |   question | answer1  | answer2  | ... |
| id        |       |  2   |   question | answer1  | answer2  | ... |
| question  |       |  3   |   question | answer1  | answer2  | ... |
| answer1   |  or   |  4   |   question | answer1  | answer2  | ... |
| answer2   |       |  5   |   question | answer1  | answer2  | ... |
| answer3   |       |  6   |   question | answer1  | answer2  | ... |
| answer... |       |  7   |   question | answer1  | answer2  | ... |
+-----------+       |-----------------------------------------------+

我的 C# Linq

        var joinedTable =
        from questions in db.Results
        join answers in db.Answers on questions.id equals answers.result_id
            into answers
        select new 
        { 
           questions.id, 
           TOTAL_ANSWERS = answers.Count(), 
           questions.SurveyDateCreated, 
           (answers.ForEach(a=> a.answer) as "Answer" + i++)
        };

最佳答案

您正在寻找的是 PIVOT。最好的方法是在 SQL 中创建一个存储过程并在 SQL 中执行 PIVOT。使用 LINQ,这是可能的,但很复杂。

使用 LINQ 进行透视: http://madhukap.blogspot.com/2011/05/pivot-with-linq.html http://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using-linq

关于c# - 自然加入.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13400652/

相关文章:

c# - 将 linq 与 PropertyInfo 结合使用

sql - 我应该如何加入这些表?

mysql - 可怕的多重连接需要将结果限制为 144

c# - 将 winform .net Framework 3.5 迁移到 4 时出错

c# - 单击按钮时中止正在运行的功能

linq - 将 dbml 中的连接字符串指向 app.config

mysql - 如何使用Left Join和子查询修复SQL查询?

c# - 如何在 MVVM 中对异步 ICommand 进行单元测试?

c# - 在尝试通过“联系我们”表格联系公司时识别发件人电子邮件 ID

linq - LINQ to SQL 是否已弃用?