如何使用LINQ填充集合中的集合?

时间:2013-09-15 13:56:00

标签: c# linq

我创建了以下LINQ代码:

 QuestionDetail questions = _questionsRepository
                .GetAll()
                .Include(q => q.Answers)
                .Select(m => new QuestionDetail
                {
                    QuestionId = m.QuestionId,
                    Text = m.Text,
                    Answers // << I am not sure how to populate this
                            // << I need to have a new collection 
                            // << created from a subset of the m.Answers
                })
                .FirstOrDefault();

我的问题是我不知道如何填充QuestionDetail中的ICollection<AnswerDetail> Answers集合。我需要的是以某种方式从m.Answers中选择并使用它来填充AnswerDetail集合。我知道我不能使用新的AnswerDetail,因为Answers是一个集合。

任何人都可以帮忙告诉我如何做到这一点。

下面我列出了一些类。为了简单起见,我从问答类中删除了一些字段。

public class QuestionDetail
{
    public int QuestionId { get; set; }
    public string Text { get; set; }
    public virtual ICollection<AnswerDetail> Answers { get; set; }
}

public class AnswerDetail
{
    public int AnswerId { get; set; }
    public string Text { get; set; }
}

public class Answer
{
    public int AnswerId { get; set; }
    public int QuestionId { get; set; }
    public Nullable<bool> Correct { get; set; }
    public Nullable<bool> Response { get; set; }
    public string Text { get; set; }
    public virtual Question Question { get; set; }
}

public class Question
{
    public Question()
    {
        this.Answers = new List<Answer>();
    }
    public int QuestionId { get; set; }
    public string Text { get; set; }
    public string Image { get; set; }
    public virtual ICollection<Answer> Answers { get; set; }
}

3 个答案:

答案 0 :(得分:2)

我可以看到这应该有效:

Answers = m.Answers.Select(a => 
              new AnswerDetail { AnswerId = a.AnswerId, 
                                 Text = a.Text }).ToList(),

您有一个Answer列表,并将其转换为AnswerDetail列表。

答案 1 :(得分:1)

如果您需要q.Answers的子集,并且您可以执行以下操作:

QuestionDetail questions = _questionsRepository
            .GetAll()
            .Include(q => q.Answers)
            .Select(m => new QuestionDetail
            {
                QuestionId = m.QuestionId,
                Text = m.Text,
                Answers = m.Answers.Where(x=>yourCondition)
            })
            .FirstOrDefault();

答案 2 :(得分:0)

试试这个:

在“外部”上取(1)而不是FirstOrDefault项目结果:

QuestionDetail questions = _questionsRepository
        .GetAll()
        .Include(q => q.Answers)
        .Take(1)
        .ToList()
        .Select(m => new QuestionDetail
        {
            QuestionId = m.QuestionId,
            Text = m.Text,
            Answers = m.Answers.Select(a => 
                              new AnswerDetail { AnswerId = a.AnswerId, 
                                                 Text = a.Text }).ToList()
        });