如何将两个对象的字段合并为一个?

时间:2013-09-18 09:18:01

标签: c# linq

我有以下

public class AnswerDetail
{
    public int AnswerId { get; set; }
    public string Text { get; set; }
    public Nullable<bool> Correct { get; set; }
    public Nullable<bool> Response { get; set; }
}
  • 我从客户端收到了一个带有Response字段的AnswerDetail 填充:AnswerDetail rfc
  • 我从数据库收到了一个带有Correct字段的AnwerDetail 填充:AnswerDetail afd

如何组合这些来制作另一个Answerdet对象,该对象从afd获取AnswerId,Text和Correct以及从rfc获取Response?

更新:删除了ClientAnswers类以简化问题

7 个答案:

答案 0 :(得分:1)

您需要创建一个新的AnswerDetail,然后只需从正确的来源设置属性。

AnswerDetail adCombined = new AnswerDetail
{
    AnswerId = afd.AnswerId,
    Text = afd.Text,
    Correct = afd.Correct,
    Response = rfc.Response
};

答案 1 :(得分:1)

AnswerDetail ans = new AnswerDetail{Correct = rfc.Correct, Response = afd.Response}

答案 2 :(得分:0)

rfc.Select(r=>
    new AnswerDetail
    {
        AnswerId =r.AnswerId,
        Text=r.Text,
        Response=r.Response,
        Correct=afd.Single(c=>c.AnswerId==r.AnswerId).Correct
    }
           );

答案 3 :(得分:0)

也许你可以试试这个:

var combined = from rfcItem in rfc.Answers
               join afdItem in afd.Answers on rfcItem.AnswerId equals afdItem.AnswerId
               select new AnswerDetail 
               { 
                   AnswerId = afdItem.AnswerId,
                   Text = afdItem.Text,
                   Correct = afdItem.Correct,
                   Response = rfcItem.Response
               };

答案 4 :(得分:0)

如果您已经拥有来自客户端的Response字段,那么实际上只是一个用DB更正结果来更新结果的情况,例如

foreach (var a in rfc)
{
    a.Correct = afd.Answers.Single(x => x.AnswerId == a.AnswerId).Select(x => x.Correct);
}

答案 5 :(得分:0)

我想每个afd总会有相应的rfc答案:

var zipped = from rows in afd.Answers
             select new AnswerDetail()
             {
                AnswerId = rows.AnswerId,
                Correct = rows.Correct,
                Response = rfc.Answers.First(r=>r.AnswerId == rows.AnswerId).Response,
                Text = rows.Text
             };

您可以将整个ClientAnswer创建为:

var zipped = new ClientAnswers()
             {
                QuestionId = yourQuestionId, 
                Answers = (from rows in afd.Answers
                          select new AnswerDetail()
                          {
                              AnswerId = rows.AnswerId,
                              Correct = rows.Correct,
                              Response = rfc.Answers.First(r => r.AnswerId == rows.AnswerId).Response,
                              Text = rows.Text
                          }).ToList()
            };

答案 6 :(得分:0)

您的信息没有说清单。

为什么不:

afd.Response = rfc.Response;