![](/img/trans.png)
[英]How to run a LINQ query on a collection of objects and a collection inside of each object
[英]LINQ query to get all data about object which is collection of objects when each item of collection has own collection
誰能給我一個關於如何解決下一個任務的提示?
我有這樣的類結構
public class Test
{
public string Title { get; set; }
public ICollection<Question> Questions { get; set; }
}
public class Question
{
public string Description { get; set; }
public ICollection<AnswerItem> AnswerItems { get; set; }
}
public class AnswerItem
{
public string Defenition { get; set; }
public bool IsCorrect { get; set; }
}
從數據庫中獲取[Test]
實體后,我得到了IQueryable<Test>
。 此外,我想知道如何獲取所有問題實體(作為列表)以及所有信息,其中每個問題項都將包含有關 AnswerItem 集合的所有信息。 我嘗試了下一個查詢,但它只返回所有答案的集合:
var questList = test.SelectMany(t => t.Questions.SelectMany(q => q.AnswerItems)).ToList();
我需要這樣的東西:
Questions = new List<Question>
{
new Question
{
Name = "Question_1",
AnswerItems = new List<AnswerItem>
{
new AnswerItem { Name = "answer_1", IsCorrect = false },
new AnswerItem { Name = "answer_2", IsCorrect = false }
}
},
new Question
{
Name = "Question_2",
AnswerItems = new List<AnswerItem>
{
new AnswerItem { Name = "answer_1", IsCorrect = false },
new AnswerItem { Name = "answer_2", IsCorrect = false }
}
}
}
您的查詢應如下所示:
var query =
from t in ctx.Tests
from q in t.Questions
select new
{
Name = q.Description,
AnswerItems = q.AnswerItems.Select(a => new
{
Name = a.Defenition,
IsCorrect = a.IsCorrect
})
.ToList()
}
};
var result = query.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.