如何在LINQ中填充数据。从字符串的每个字符的值中选择?

时间:2015-03-24 14:46:50

标签: c# linq

我有一个包含问答数据的集合。请注意,Result的值是一个字符串,表示答案的true或false值:

这是一个简单的例子:

List<ResultDTO> result1 = new List<ResultDTO> () {
   new ResultDTO () { Id=1, Text= "abc", Result="001", AnswerId= 1, AnswerText= "Aab1" },
   new ResultDTO () { Id=1, Text= "abc", Result="001", AnswerId= 2, AnswerText= "Aab2" },
   new ResultDTO () { Id=1, Text= "abc", Result="001", AnswerId= 3, AnswerText= "Aab3" },
   new ResultDTO () { Id=1, Text= "def", Result="110", AnswerId= 4, AnswerText= "Aab4" },
   new ResultDTO () { Id=1, Text= "def", Result="110", AnswerId= 5, AnswerText= "Aab5" },
   new ResultDTO () { Id=1, Text= "def", Result="110", AnswerId= 6, AnswerText= "Aab6" }
};

在此示例中,AnswerId 3,4和5将是正确的

我使用以下代码按ID,文本和结果分组

var questions = result1
  .GroupBy(
    r => new { r.Id, r.Text, r.Result },
    (key, results) => new QuestionDTO {
      Id = key.Id,
      Text = key.Text,
      Answers = results
        .Select(r => new AnswerDTO { 
           AnswerId = r.AnswerId, 
           AnswerText = r.AnswerText,
           AnswerResult =  })
        .ToList()
    }
  )
  .ToList();

有人可以帮我告诉我如何填充AnswerResult栏。这个数据正在进行中 在r.Result,但我不知道如何使用数据

1 个答案:

答案 0 :(得分:1)

键包含您在论坛中指定的所有属性:

var questions = result1
    .GroupBy(
    r => new { r.Id, r.Text, r.Result },
    (key, results) => new QuestionDTO 
    {
        Id = key.Id,
        Text = key.Text,
        Answers = results
        .Select(r => new AnswerDTO 
        { 
            AnswerId = r.AnswerId, 
            AnswerText = r.AnswerText,
            AnswerResult = key.Result 
        })
        .ToList()
     }
  )
  .ToList();