C# 聚合。Linq到对象查询
我有三节课C# 聚合。Linq到对象查询,c#,linq-to-objects,C#,Linq To Objects,我有三节课 public class Test { private List<Question> _questions; private string _text; public string Text { get { return _text; } } //... } public class Question { private List<Answer> _ans
public class Test
{
private List<Question> _questions;
private string _text;
public string Text
{
get
{
return _text;
}
}
//...
}
public class Question
{
private List<Answer> _answers;
private string _text;
public string Text
{
get
{
return _text;
}
}
//...
}
public class Answer
{
private string _text;
private bool _isCorrect;
public string Text
{
get
{
return _text;
}
}
public bool isCorrect
{
get
{
return _isCorrect;
}
}
//...
}
公共类测试
{
私人列表问题;
私有字符串_文本;
公共字符串文本
{
得到
{
返回文本;
}
}
//...
}
公开课问题
{
私人名单(答案),;
私有字符串_文本;
公共字符串文本
{
得到
{
返回文本;
}
}
//...
}
公开课答案
{
私有字符串_文本;
私人住宅是正确的;
公共字符串文本
{
得到
{
返回文本;
}
}
公共场所是正确的
{
得到
{
返回正确;
}
}
//...
}
我需要从问题中选择文本,从答案中选择文本,其中答案是正确的。
我只能选择正确的答案。
测试t;
//初始化t
var r=t.SelectMany(q=>q)。其中(a=>a.isCorrect==true);
我的问题是:
如何从问题和答案中选择文本,其中答案是正确的。
我需要对对象进行linq查询。假设
Test
实现IEnumerable
和问题实现IEnumerable
:
首先,你的问题和答案是私人的。我假设您有一个公共访问器,分别提供问题和答案
试试这个:
var results = from q in t.Questions
where q.Answers.Any(a=>a.isCorrect)
select new {Question = q, CorrectAnswers = q.Answers.Where(a=>a.isCorrect)};
您现在可以参考结果。问题和结果。正确答案。您还可以选择一个新问题,其中答案列表仅包含正确答案。您的问题是什么?请编辑您的问题以包含实际问题。我无法访问测试中的问题。我只能找一个统计员。
var questionsWithCorrectAnswers = myTest
.SelectMany(q => q.Where(a => a.IsCorrect)
.Select(a => new { Question = q, Answer = a }));
var results = from q in t.Questions
where q.Answers.Any(a=>a.isCorrect)
select new {Question = q, CorrectAnswers = q.Answers.Where(a=>a.isCorrect)};