I am not so far good in linq so was trying to write Linq query to check whether child topic node exist if code=”111″ && isDisplay=”Y” or not.i am using .Any condition in Second method but still i am not sure about this.
static void Main(string[] args)
{
XElement rootElement = XElement.Load("TestXML.xml");
int StyCode = 1;
var lv1s = from lv1 in rootElement.Descendants("Class")
where lv1.Attribute("Code").Value.Equals("001")
select (from ltd in lv1.Descendants("Subject")
where ltd.Attribute("Course").Value.Equals("Engish")
select GetChildFromSubject(StyCode, ltd)).FirstOrDefault();
}
private static bool GetChildFromSubject(int styCode, XElement subject)
{
if (styCode == 0)
return subject.Attribute("SpeciaGuest").Value.Equals("Y");
else
{
//Below is the main issue with and condition on attributes.
return subject.Attribute("AllTeachers").Value.Equals("Y") ||
subject.Elements("Topic").Attributes("Code")
.Any(x => x.Value.Equals("111")) && subject.Elements("Topic").Attributes("isDisplay")
.Any(y => y.Value.Equals("Y"));
}
}
Below is XML file
<Class Code="002">
<Subject Course="Math" AllTeachers='Y' SpeciaGuest='N'>
<Topic Code="1" isDisplay="Y">LAW1</Topic>
<Topic Code="2" isDisplay="Y">
LAW2
</Topic>
<Topic Code="3" isDisplay="N">
LAW3
</Topic>
</Subject>
<Subject Course="Engish" AllTeachers='N' SpeciaGuest='Y'>
<Topic Code="111" isDisplay="Y">LAW1</Topic>
</Subject>
<Subject Course="History" AllTeachers='Y' SpeciaGuest='Y'></Subject>
</Class>
Per your comment:
If you’re trying to return the TOPIC node if code=111 and isDiaply=Y, then here is the LINQ query in one shot: