I am using following linq query to work with XML file..
XElement rootElement = XElement.Load(@"test.xml");
int StyCode;
var lv1s = from lv1 in rootElement.Descendants("Class")
where lv1.Attribute("Code").Value.Equals("002")
select new
{
Children = from ltd in lv1.Descendants("Subject")
where ltd.Attribute("Course").Value.Equals("Math")
select new
{
****//In This below section need result on condition based... ****
if(StyCode=0)
{
Children1 = ltd.Attribute("AllTeachers").Value.Equals("Y") ? true : false
}
else
{
Children2 = ltd.Attribute("SpeciaGuest").Value.Equals("Y") ? true : ltd.Elements("Topic").Attributes("Code").Where(x => x.Value.Equals("1")).FirstOrDefault() != null ? true : false
}
}
};
Below is my XML Structure..
<?xml version="1.0" encoding="utf-8" ?>
<Document>
<Class Code="001">
<Subject Course="Math" AllTeachers='N' SpeciaGuest='N'></Subject>
<Subject Course="Engish" AllTeachers='Y' SpeciaGuest='Y'></Subject>
<Subject Course="History" AllTeachers='Y' SpeciaGuest='Y'></Subject>
</Class>
<Class Code="002">
<Subject Course="Math" AllTeachers='Y' SpeciaGuest='N'>
<Topic Code="1">LAW1</Topic>
<Topic Code="2">
LAW2
</Topic>
<Topic Code="3">
LAW3</Topic>
</Subject>
<Subject Course="Engish" AllTeachers='Y' SpeciaGuest='Y'></Subject>
<Subject Course="History" AllTeachers='Y' SpeciaGuest='Y'></Subject>
</Class>
</Document>
Please let me know, how I can use condition to select multiple select result. Also let me know using resharper in this linq query will be fine?.
Because
if(StyCode=0)isn’t based on the current item in the sequence, you can pull theifoutside of the query:Also note that because both of the
Selectclauses are selecting a single item, you don’t need an anonymous type, just select that item. That results in this:So this is simple, and nice, but has a lot of code duplication, which is not no nice. Another road to travel down is to create a method that takes an
XElementthat representsltdas well as an integerStyCodeand returns a boolean indicating the appropriate value. It’s a simple enough method to write:Now we only need one query:
Much better.