是否有LINQ方式将数据从平面移动到父/子集合?

时间:2015-03-24 08:07:08

标签: c# linq

我有一个包含问答数据的集合。这是一个简单的例子:

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

更新

这是我按照马丁的建议尝试创建对象的代码:

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

我想做的是把它变成一个以客观为导向的形式?我已经创建了 两个新类:

    public partial class QuestionDTO
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public string Answer { get; set; }
        public ICollection<Answer> Answers { get; set; }

    }

    public partial class AnswerDTO
    {
        public int AnswerId { get; set; }
        public string AnswerText { get; set; }
    }

    public class ResultDTO
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public int AnswerId { get; set; }
        public string AnswerText { get; set; }
    }

1 个答案:

答案 0 :(得分:3)

您可以使用GroupBy提取问题和答案:

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

Question.Answer属性为null,因为您尚未为此属性提供任何值。

结果如下:

Id | Text | Answers
---+------+----------------------
1  | abc  | AnswerId | AnswerText
   |      | ---------+-----------
   |      | 1        | Aab1
   |      | 2        | Aab2
   |      | 3        | Aab3
   |      | ---------+-----------
---+------+----------------------
2  | def  | AnswerId | AnswerText
   |      | ---------+-----------
   |      | 4        | Aab4
   |      | 5        | Aab5
   |      | 6        | Aab6
   |      | ---------+-----------
---+------+----------------------