由于Cannot convert lambda expression to delegate type
,我无法获得答案属性。这些是我的课程和我的查询:
var file = XDocument.Load("QuestionsTest.xml");
var questions = from answers in file.Root.Elements("Question").Elements("Answers").Elements("Answer")
select new Answer
{
Text = (string)answers,
Correct = (string)answers.Elements("Answer").Single(answer=>(string)answer.Attribute("Correct"))
};
public class Answer
{
public int AnswerID { get; set; }
public string Text { get; set; }
public string Correct { get; set; }
public int Stats { get; set; }
public int QuestionID { get; set; }
}
public class Question
{
public virtual List<Answer> Answers { get; set; }
}
我的XML看起来像这样:
<?xml version="1.0" encoding="utf-8" ?>
<Questions Subject="ADO.NET">
<Question NumberOfAnswers="1">
<Text>Which class should you use to manage multiple tables and relationships among them?</Text>
<Answers>
<Answer>DataRow</Answer>
<Answer>DataView</Answer>
<Answer>DataTable</Answer>
<Answer Correct="Yes">DataSet</Answer>
</Answers>
</Question>
</Questions>
如何获得答案的属性?
答案 0 :(得分:1)
Enumerable.Single
接受Func<T,bool>
委托,该委托应返回 boolean 值。您正在传递返回XAttribute
值的委托。您应将属性值与Yes
字符串进行比较以返回布尔结果:
Single(answer => (string)answer.Attribute("Correct") == "Yes")
这将解决您的错误。但我认为你也应该改变你的查询逻辑。首先更改Answer
类,并使Correct
属性布尔值:
public class Answer
{
public int AnswerID { get; set; }
public string Text { get; set; }
public bool IsCorrect { get; set; }
public int Stats { get; set; }
public int QuestionID { get; set; }
}
查询应如下所示:
var xdoc = XDocument.Load("QuestionsTest.xml");
var questions =
from q in xdoc.Descendants("Question")
select new Question {
Answers = (from a in q.Descendants("Answer")
select new Answer {
Text = (string)a,
IsCorrect = (string)a.Attribute("Correct") == "Yes"
}).ToList()
};
答案 1 :(得分:1)
var questions = from answers in
file.Root.Elements("Question").Elements("Answers").Elements("Answer")
select new Answer
{
Text = (string)answers,
Correct = (string)answers.Attribute("Correct")
};