如何将保存为01010位的数据转换为类对象中的字段?

时间:2014-07-23 07:57:46

标签: c#

我有两个包含真/假数据的变量。第一个变量可以为null,但第二个变量始终为非null。两个变量的长度始终相同。

var AnswerGridCorrect = "000111"; // or null
var AnswerGridResponses = "000011";

如何将此数据更改为面向对象的表单。我已经创建了类,这些都在下面。这是我在转换为JSON时需要输出的样子:

"answers":[        // Json conversion made Answers into answers
   {"correct":null,"response":true},
   {"correct":null,"response":true},
   {"correct":null,"response":true},
   {"correct":null,"response":false}
 }

请注意,我使用LINQ输出数据,所以我认为我需要的是一个带有如下参数的函数:

 .Select((t, index) => new  {
                Answer = t.Answer,
                Answers = makeAnswer(t.AnswerGridCorrect,
                                     t.AnswerGridResponses)
                });

我不确定这是否有帮助,但是当我从JSON执行此操作时,我正在使用这些类:

public class AnswerRow
{
    public bool? Correct { get; set; }
    public bool Response { get; set; }
}

public class AnswerRowList
{
    public IList<AnswerRow> AnswerRows { get; set; }
}

2 个答案:

答案 0 :(得分:0)

以下是makeAnswers方法的实现:

public List<AnswerRow> makeAnswers(string c, string r)
{
   var result = new List<AnswerRow>();
   for(var i=0; i<r.Length; i++)
   {
       result.Add(
        new AnswerRow { 
                 Correct = c!=null?new Nullable<bool>(c[i]=='1'):null,
                 Response = r[i]=='1'
        });
   }
   return result;
}    

答案 1 :(得分:0)

Rene的回答可能是正确的,但这是(不必要的复杂)Linq方式:

AnswerRowList MakeAnswer(string answerGridCorrect, string answerGridResponses)
{
    return new AnswerRowList()
    {
        AnswerRows = answerGridResponses.Zip(
            answerGridCorrect == null ?
                Enumerable.Repeat<bool?>(null, answerGridResponses.Length) :
                answerGridCorrect.Select(x => new Nullable<bool>(x == '1')),
            (r, c) => new AnswerRow()
            {
                Correct = c,
                Response = r == '1'
            }).ToList()
    };
}