lundi 16 mars 2020

Better way to check the last item of the same type in the if statement

I've written the code that reads .xml document. This code works pretty well but I want to consider other possible improvements.

The structure of the document is:

<rootElement>
     <firstType>someValue</firstType>
     <firstType>someValue</firstType>
     <firstType>someValue</firstType>
     <firstType>someValue</firstType>
     ...
     <firstType>someValue</firstType>
     <secondType>someValue</firstType>
     <thirdType>someValue</firstType>
</rootElement>

So, there are lots of elements of the 'firstType' followed by two respective elements of 'secondType' and 'thirdType'. I need to check if the the current XElement of the foreach iteration is the last 'firstType' element. If the statement is true, do some operations:

foreach (XElement first in hisDoc.Root.XPathSelectElements("firstType")) {
     // some operations
     if ((first.NextNode == hisDoc.Root.XPathSelectElement("secondType")) || (hour.NextNode == hisDoc.Root.XPathSelectElement("thirdType"))){
          // some operations
     }
}

I've coped with the task, though it might be enhanced somehow. I mean if there have been added more other elements e.g. 'fourthType'. It would inconvenient to make longer if statement. I use LINQtoXML(XDocument) and don't wanna change to XmlDocument since it's slower. Moreover XDocument is much more easier to use.

I think it must be more efficient way to do that task.

Aucun commentaire:

Enregistrer un commentaire