尝试将记录合并到1个结果集中

时间:2014-02-07 16:39:02

标签: c# linq

我正在尝试创建与每个问题相关的问题和答案的结果集:

var  myQs = from q in Questions  select new {q.QuestionID, q.ID, q.Description};

var myAs = from ad in AnswerDetails where ad.Answer.KeyID == 4590 select ad;

我想建立一份所有问题和答案的清单(无论每个问题是否有答案)。

所以我可以这样:

  

Question1Text | Question1Answer

     

Question2Text |

     

Question3Text | Question3Answer

     

Question4Text | Queston4Answer

     

Question5Text |

我使用的是LinqPad,但我无法使用Concat语句使其工作。

4 个答案:

答案 0 :(得分:1)

你想要这样的东西吗?

var questionWithAnswers = Questions
                         .Select(q => new { 
                                    Question = q,
                                    Answer = AnswerDetails
                                   .FirstOrDefault(a => a.Answer.KeyID == q.ID) ?? ""
                          }).ToList();

var resultSet = String.Join(Environment.NewLine, questionWithAnswers
                                                .Select(x => String.Format("{0} | {1}",x.Question.Description, x.Answer));

答案 1 :(得分:1)

您可以使用concat中的unionlinq来合并它们,union除了distinct之外,concat合并它们没有distinct,但你需要在same类型中有两个列表,例如你可以这样做来合并它们

(from q in Questions  select new {code = q.QuestionID, id = q.ID, desc = q.Description})
.Union(from ad in AnswerDetails where ad.Answer.KeyID == 4590 select new {code = ad.??, id = ad.??, desc = ad.??})

??上您需要的字段填写answer,并且与您从Question (id, code, desc)获取的字段相同,如果您可以从任何文件中获取更多文件表,您必须将它们添加到您选择并返回的anonymouse类型,并按表格中的默认值填充它们,您没有任何值来填充它们,

此外,在您的情况下,您需要执行left join,例如:

var query = (from q in Questions
    join u in AnswerDetails on q.ID equals u.QUESTION_FOREIGN_KEY into JoinedList
    from u in JoinedList.DefaultIfEmpty()
    select new {question = q, answer = u }
).ToList()

答案 2 :(得分:1)

您想要执行左连接。之所以这么称呼是因为左侧部分(问题,在您的情况下)是必需的,但正确的部分(答案)是可选的。 LINQ没有简化这一点,但可以做到。

你没有提供AnswerDetails的样子,所以我只能在这里猜测:

var myQs = from q in Questions  select new {q.QuestionID, q.ID, q.Description};
var myAs = from ad in AnswerDetails where ad.Answer.KeyID == 4590 select ad;

var joined = from q in myQs
             join a in myAs on q.ID equals a.QuestionID into answers
             from a in answers.DefaultIfEmpty()
             select new
             {
                 Text = q.Description,
                 Answer = a != null ? a.AnswerText : string.Empty
             };

答案 3 :(得分:1)

你必须离开两个列表的连接,因为在答案列表中,你可能没有一些问题的答案:

  var result = (from qn in questions
                      join ad in answers on qn.ID equals ad.KeyId
                      into add
                      from ad2 in add.DefaultIfEmpty()
                      select new { sd = qn.Description + "|" + ((ad2 == null) ? "" : ad2.text) }).ToList();