I'm reading the Cormen algorithms book (binary search tree chapter) and it says that there are two ways to traverse the tree without recursion:
using stack and
a more complicated but elegant
solution that uses no stack but
assumes that two pointers can be
tested for equality
I've implemented the first option (using stack), but don't know how to implement the latter.
This is not a homework, just reading to educate myself.
Any clues as to how to implement the second one in C#?
Sure thing. You didn't say what kind of traversal you wanted, but here's the pseudocode for an in-order traversal.
t = tree.Root;
while (true) {
while (t.Left != t.Right) {
while (t.Left != null) { // Block one.
t = t.Left;
Visit(t);
}
if (t.Right != null) { // Block two.
t = t.Right;
Visit(t);
}
}
while (t != tree.Root && (t.Parent.Right == t || t.Parent.Right == null)) {
t = t.Parent;
}
if (t != tree.Root) { // Block three.
t = t.Parent.Right;
Visit(t);
} else {
break;
}
}
To get pre- or post-order, you rearrange the order of the blocks.
Assuming that the nodes in the tree are references and the values are references, you can always call the static ReferenceEquals method on the Object class to compare to see if the references for any two nodes/values are the same.
Related
Switch case statements are good to replace nested if statements if we have the same condition but different criteria. But what is a good approach if those nested if statements all have different and unique conditions? Do I have any alternate options to replace a dozen if else statements nested inside each other?
Sample Code:
Note: I know this is extremely unreadable - which is the whole point.
Note: All conditions are unique.
...
if (condition) {
// do A
} else {
if (condition) {
// do B
if (condition) {
if (condition) {
if (condition) {
// do C
if (condition) {
// do D
if (condition) {
// do E
} else {
if (condition) {
// do F
}
}
}
}
if (condition) {
// do G
if (condition) {
// do H
if (condition) {
// do I
} else {
// do J
}
}
}
}
}
}
The best approach in this case is to chop up the thing into appropriately named separate methods.
I had to check this was Stackoverflow not DailyWTF when I saw the code!!
The solution is to change the architecture and use interfaces and polymorphism to get around all the conditions. However that maybe a huge job and out of the scope of an acceptable answer, so I will recommend another way you can kinda use Switch statements with unique conditions:
[Flags]
public enum FilterFlagEnum
{
None = 0,
Condition1 = 1,
Condition2 = 2,
Condition3 = 4,
Condition4 = 8,
Condition5 = 16,
Condition6 = 32,
Condition7 = 64
};
public void foo(FilterFlagEnum filterFlags = 0)
{
if ((filterFlags & FilterFlagEnum.Condition1) == FilterFlagEnum.Condition1)
{
//do this
}
if ((filterFlags & FilterFlagEnum.Condition2) == FilterFlagEnum.Condition2)
{
//do this
}
}
foo(FilterFlagEnum.Condition1 | FilterFlagEnum.Condition2);
#Tar suggested one way of looking at it. Another might be.
Invert it.
if (myObject.HasThing1)
{
if(myObject.HasThing2)
{
DoThing1();
}
else
{
DoThing2();
}
}
else
{
DoThing3();
}
could be
DoThing1(myObject.HasThing1);
DoThing2(myObject.HasThing2);
DoThing3(myObject.HasThing3);
So each Do method makes the minimum number of tests, if any fail the it does nothing.
You can make it a bit cleverer if you want to break out of the sequence in few ways.
No idea whether it would work for you, but delegating the testing of the conditions is often enough of a new way of looking at things, that some simplifying factor might just appear as if by magic.
In my point of view there exists two main methods to eliminate nested conditions. The first one is used in more special cases when we have only one condition in each nested conditions like here:
function A(){
if (condition1){
if (condition2){
if (condition3){
// do something
}
}
}
}
we can just go out from the opposite condition with return:
function A(){
if (condition1 == false) return;
if (condition2 == false) return;
if (condition3 == false) return;
// do something
}
The second one is using a condition decomposition and can be treated as more universal than the first one. In the case when we have a condition structure like this, for example:
if (condition1)
{
// do this 1
}
else
{
if (condition2)
{
// do this 2
}
}
We can implement a variables for each particular condition like here:
bool Cond1 = condition1;
bool Cond2 = !condition1 && condition2;
if (Cond1) { //do this 1 }
if (Cond2) { //do this 2 }
If that really is the business logic then the syntax is OK. But I have never seen business logic that complex. Draw up a flow chart and see if that cannot be simplified.
if (condition)
{
// do this
}
else
{
if (condition)
{
// do this
}
}
can be replaced with
if (condition)
{
// do this
}
else if (condition)
{
// do this
}
But again step back and review the design. Need more than just an else if clean up.
I feel your pain.
My situation required writing many (>2000) functional tests that have been customer specified for a large, expensive piece of equipment. While most (>95%) of these tests are simple and have a straight forward pass/fail check dozens fall into the "multiple nested if this do that else do something different" at depths similar or worse than yours.
The solution I came up with was to host Windows Workflow within my test application.
All complex tests became Workflows that I run with the results reported back to my test app.
The customer was happy because they had the ability to:
Verify the test logic (hard for non programmers looking at deeply nested if/else C# - easy looking at a graphical flowchart)
Edit tests graphically
Add new tests
Hosting Windows Workflow (in .NET 4/4.5) is very easy - although it may take you a while to get your head around "communications" between the Workflows and your code - mostly because there are multiple ways to do it.
Good Luck
I have a function that calls a lot of other functions from different objects. Each function has to return true before calling the next one. As you can see I am using too many if statements. How can I improve the code and make it neater? Thanks
bool ISOKToDoSomthing()
{
boo retVal = false;
retVal = ObjA.CheckVersion(oldVersion);
if(retVal)
{
retVal = objB.CheckUserRight();
}
if(retVal)
{
retVal = ObjC.ISDBExist();
}
if(retVal)
{
retVal = OjbD.ISServerUp(ServerName);
}
//tons of similar code as above
.........
return retVal;
}
return
ObjA.CheckVersion(oldVersion) &&
objB.CheckUserRight() &&
ObjC.ISDBExist() &&
OjbD.ISServerUp(ServerName);
My advice: do nothing to this code without a clear business case for making the change.
Your code is clear, obvious, likely correct, easy to maintain and easy to debug. Why on earth would you want to change it in any way? Spend your time adding value by fixing bugs and adding features, not by changing working code unnecessarily. When your boss asks you "so what did you do today?" the answer should not be "I increased our schedule risk to by making unnecessary cosmetic changes to correct, working, already-debugged code".
Now, if there really is a problem here, the problem is likely not that the code is hard to read, but rather that the code rigidly encodes what ought to be a user-configurable business process. In that case, create an object called "Workflow" that encodes the business process, and an engine which evaluates an arbitrary workflow. Then construct an instance of that object that represents the desired workflow based on input from the user.
That actually adds value for the user; the user cares not a bit whether you use nested "if" statements or not.
if (!ObjA.CheckVersion(oldVersion)) return false;
if (!ObjB.CheckUserRight()) return false;
if (!ObjC.IsDBExist()) return false;
if (!ObjD.IsServerUp(serverName)) return false;
... your other checks ...
return true;
The short-circuiting of && is useful for a few conditions, but if you have "tons" of them, IMO that's way too much to try and stick in one statement.
A combination of the two might be useful, though. More useful still would be to condense some of these checks together into bigger chunks (but smaller than IsOKToDoSomething). For instance, check whether you have access to the database (whether it exists, whether you can log in to it, etc) all at once
Truth be told, the fact that you have so many objects to check hints at a design issue -- namely, you're trying to do too much at once, or you have a "god object" somewhere that has its little tentacles in every aspect of the system. You might want to look at fixing that.
return ObjA.CheckVersion(oldVersion) && objB.CheckUserRight() && ObjC.ISDBExist() && OjbD.ISServerUp(ServerName)
The && operator will short-circuit, so you can chain them like so:
bool ISOKToDoSomthing()
{
return
ObjA.CheckVersion(string oldVersion) &&
objB.CheckUserRight() &&
ObjC.ISDBExist() &&
OjbD.ISServerUp(ServerName) &&
//tons of similar code as above
.........
}
bool ISOKToDoSomthing()
{
return ObjA.CheckVersion(string oldVersion) &&
ObjB.CheckUserRight() &&
ObjC.ISDBExist() &&
OjbD.ISServerUp(ServerName);
}
Perhaps?
retVal = objB.CheckUserRight() && ObjC.ISDBExist() && OjbD.ISServerUp(ServerName);
etc.
A side note, you can test for example, if objB is null before calling a method on it in one statement (the code will break execution as soon as a condition has not been met, i.e. won't call the next condition) so you don't need lots of if(objB != null) type statements. E.g.:
retVal = (objB != null && objB.CheckUserRight()) && (ObjC != null && ObjC.ISDBExist()) && (OjbD != null && OjbD.ISServerUp(ServerName));
You can leverage the fact that C# does short-circuit evaluation:
return
ObjA.CheckVersion(oldVersion) &&
objB.CheckUserRight() &&
ObjC.ISDBExist() &&
OjbD.ISServerUp(ServerName);
Editing to fix syntax on CheckVersion's parameters
How about using and:
retVal = ObjA.CheckVersion(oldVersion) &&
objB.CheckUserRight() &&
ObjC.ISDBExist() &&
OjbD.ISServerUp(ServerName);
return retval;
To make the code less wordy, you could try a while loop. Given that your method here is to not ever change the value of your original value if it /ever/ turns false, then it would be while(retval) {} and iterate over a list of actions. Personally, I think this is ugly. Consider using a switch, or even (yuck on this, but it would work) a bitwise enum.
From my perspective, when I see myself writing code like this, I've made a grave architectural mistake somewhere and I should really rethink the reason behind making this call. Perhaps you should take another look at your logic, rather than just your code. Sit down and draw some boxes and work a bit more in the design phase and you might find yourself building things very differently.
edit: or yeah, like everyone else did, you can make your iteration a single if statement. Again, this is a bigger problem than a long list of booleans.
It depends on how much you want to change. Perhaps instead of returning a bool from your sub-methods, you could throw an exception.
bool retVal = true;
try
{
ObjA.CheckVersion(oldVersion);
objB.CheckUserRight();
ObjC.ISDBExist();
OjbD.ISServerUp(ServerName);
}
catch (SomeException ex)
{
// Log ex here.
retVal = false;
}
return retVal;
If you do something like this, IsDBExist probably isn't the best name (since Is generally translates to "returns a bool" in my mind), but you get the picture.
Cyclomatic Complexity will be high for methods with a high number of decision statements including if/while/for statements. So how do we improve on it?
I am handling a big project where I am supposed to reduced the CC for methods that have CC > 10. And there are many methods with this problem. Below I will list down some eg of code patterns (not the actual code) with the problems I have encountered. Is it possible that they can be simplified?
Example of cases resulting in many decision statements:
Case 1)
if(objectA != null) //objectA is a pass in as a parameter
{
objectB = doThisMethod();
if(objectB != null)
{
objectC = doThatMethod();
if(objectC != null)
{
doXXX();
}
else{
doYYY();
}
}
else
{
doZZZ();
}
}
Case 2)
if(a < min)
min = a;
if(a < max)
max = a;
if(b > 0)
doXXX();
if(c > 0)
{
doYYY();
}
else
{
doZZZ();
if(c > d)
isTrue = false;
for(int i=0; i<d; i++)
s[i] = i*d;
if(isTrue)
{
if(e > 1)
{
doALotOfStuff();
}
}
}
Case 3)
// note that these String Constants are used elsewhere as diff combination,
// so you can't combine them as one
if(e.PropertyName.Equals(StringConstants.AAA) ||
e.PropertyName.Equals(StringConstants.BBB) ||
e.PropertyName.Equals(StringConstants.CCC) ||
e.PropertyName.Equals(StringConstants.DDD) ||
e.PropertyName.Equals(StringConstants.EEE) ||
e.PropertyName.Equals(StringConstants.FFF) ||
e.PropertyName.Equals(StringConstants.GGG) ||
e.PropertyName.Equals(StringConstants.HHH) ||
e.PropertyName.Equals(StringConstants.III) ||
e.PropertyName.Equals(StringConstants.JJJ) ||
e.PropertyName.Equals(StringConstants.KKK))
{
doStuff();
}
Case 1 - deal with this simply by refactoring into smaller functions. E.g. the following snippet could be a function:
objectC = doThatMethod();
if(objectC != null)
{
doXXX();
}
else{
doYYY();
}
Case 2 - exactly the same approach. Take the contents of the else clause out into a smaller helper function
Case 3 - make a list of the strings you want to check against, and make a small helper function that compares a string against many options (could be simplified further with linq)
var stringConstants = new string[] { StringConstants.AAA, StringConstants.BBB etc };
if(stringConstants.Any((s) => e.PropertyName.Equals(s))
{
...
}
You should use the refactoring Replace Conditional with Polymorphism to reduce CC.
The difference between conditional an polymorphic code is that the in polymorphic code the decision is made at run time. This gives you more flexibility to add\change\remove conditions without modifying the code. You can test the behaviors separately using unit tests which improves testability. Also since there will be less conditional code means that the code is easy to read and CC is less.
For more look into behavioral design patterns esp. Strategy.
I would do the first case like this to remove the conditionals and consequently the CC. Moreover the code is more Object Oriented, readable and testable as well.
void Main() {
var objectA = GetObjectA();
objectA.DoMyTask();
}
GetObjectA(){
return If_All_Is_Well ? new ObjectA() : new EmptyObjectA();
}
class ObjectA() {
DoMyTask() {
var objectB = GetObjectB();
var objectC = GetObjectC();
objectC.DoAnotherTask(); // I am assuming that you would call the doXXX or doYYY methods on objectB or C because otherwise there is no need to create them
}
void GetObjectC() {
return If_All_Is_Well_Again ? new ObjectC() : new EmptyObjectC();
}
}
class EmptyObjectA() { // http://en.wikipedia.org/wiki/Null_Object_pattern
DoMyTask() {
doZZZZ();
}
}
class ObjectC() {
DoAnotherTask() {
doXXX();
}
}
class EmptyObjectB() {
DoAnotherTask() {
doYYY();
}
}
In second case do it the same was as first.
In the third case -
var myCriteria = GetCriteria();
if(myCriteria.Contains(curretnCase))
doStuff();
IEnumerable<Names> GetCriteria() {
// return new list of criteria.
}
I'm not a C# programmer, but I will take a stab at it.
In the first case I would say that the objects should not be null in the first place. If this is unavoidable (it is usually avoidable) then I would use the early return pattern:
if ( objectA == NULL ) {
return;
}
// rest of code here
The second case is obviously not realistic code, but I would at least rather say:
if ( isTrue && e > 1 ) {
DoStuff();
}
rather than use two separate ifs.
And in the last case, I would store the strings to be tested in an array/vector/map and use that containers methods to do the search.
And finally, although using cyclomatic complexity is "a good thing" (tm) and I use it myself, there are some functions which naturally have to be a bit complicated - validating user input is an example. I often wish that the CC tool I use (Source Monitor at http://www.campwoodsw.com - free and very good) supported a white-list of functions that I know must be complex and which I don't want it to flag.
The last if in case 2 can be simplified:
if(isTrue)
{
if(e > 1)
{
can be replaced by
if(isTrue && (e>1))
case 3 can be rewritten as:
new string[]{StringConstants.AAA,...}
.Contains(e.PropertyName)
you can even make the string array into a HashSet<String> to get O(1) performance.
At some time there will be a large amount of records, about 50,000.
with that in mind is the method GetEquipmentRecord up to the task.
thanks for you opinions.
c# ,net 2,0
public enum EquipShift { day, night };
public class EquipStatusList : List<EquipStatus>
{
string SerialFormat = "yyyyMMdd";
int _EquipmentID;
string _DateSerial;
EquipShift _Shift;
public EquipStatus GetEquipmentRecord(int equipmentID, EquipShift shift,
DateTime date)
{
_DateSerial = date.ToString(SerialFormat);
_Shift = shift;
_EquipmentID = equipmentID;
return this.Find(checkforEquipRecord);
}
bool checkforEquipRecord(EquipStatus equip)
{
if ((equip.EquipmentID == _EquipmentID)
&& (equip.Shift == _Shift)
&& (equip.Date.ToString(SerialFormat) == _DateSerial))
return true;
else
return false;
}
}
update :
I have changed the evaluation to read
if ((equip.Date.Date == _date.Date) && (equip.EquipmentID == _EquipmentID) && (equip.Shift == _Shift) )
not sure it that helps
Without commenting on your choice of algorithm, we can say that it probably is optimized enough.
You've got an O(n) find() in there; searching a sorted list with a binary search would be O(lg n) and searching a hash-set (or Dictionary in C# 2.0) would be O(1) for example. Hash-set would obviously be the way to go if you were calling this function often.
But bottlenecks are rarely where you expect them, so that you ask the question on this particular instance means that, on balance, profiling later will actually show that the big slowdowns are elsewhere.
You could speed this up considerably by implementing a suitable GetHashCode method and using a System.Collections.Generic.HashSet<EquipStatus> as the backing container. However, as it's not entirely clear how you are using your class (i.e. which other List<T> methods you use), ymmv.
No, it is not. Your whole construct is not able to be used in a multitasking environment. You are storing the details to search for as instance members of the class. I would take advantage of PLINQ (Parallel Linq) and the usual operators, also I wouldn't derive from the List itself, but offer an extension method like this:
public static EquipStatus GetEquipmentRecord(this IEnumerable<EquipStatus> list, int equipmentID, EquipShift shift, DateTime date)
{
return list.AsParallel().FirstOrDefault(e => e.EquipmentID == equipmentID && e.Shift == shift, e.Date.Date == date.Date);
}
By this, multiple searches at the same time are possible.
well an obvious way to improve your checkForEquipRecord method is to change
if ((equip.Date.Date == _date.Date) && (equip.EquipmentID == _EquipmentID) && (equip.Shift == _Shift) )
return true;
else
return false;
to just return (equip.Date.Date == _date.Date) && (equip.EquipmentID == _EquipmentID) && (equip.Shift == _Shift)
As far as efficiency goes, it might already be an optimization that the JIT compiler makes.
As part of the base class for some extensive unit testing, I am writing a helper function which recursively compares the nodes of one XmlDocument object to another in C# (.NET). Some requirements of this:
The first document is the source, e.g. what I want the XML document to look like. Thus the second is the one I want to find differences in and it must not contain extra nodes not in the first document.
Must throw an exception when too many significant differences are found, and it should be easily understood by a human glancing at the description.
Child element order is important, attributes can be in any order.
Some attributes are ignorable; specifically xsi:schemaLocation and xmlns:xsi, though I would like to be able to pass in which ones are.
Prefixes for namespaces must match in both attributes and elements.
Whitespace between elements is irrelevant.
Elements will either have child elements or InnerText, but not both.
While I'm scrapping something together: has anyone written such code and would it be possible to share it here?
On an aside, what would you call the first and second documents? I've been referring to them as "source" and "target", but it feels wrong since the source is what I want the target to look like, else I throw an exception.
Microsoft has an XML diff API that you can use.
Unofficial NuGet: https://www.nuget.org/packages/XMLDiffPatch.
I googled up a more complete list of solutions of this problem today, I am going to try one of them soon:
http://xmlunit.sourceforge.net/
http://msdn.microsoft.com/en-us/library/aa302294.aspx
http://jolt.codeplex.com/wikipage?title=Jolt.Testing.Assertions.XML.Adaptors
http://www.codethinked.com/checking-xml-for-semantic-equivalence-in-c
https://vkreynin.wordpress.com/tag/xml/
http://gandrusz.blogspot.com/2008/07/recently-i-have-run-into-usual-problem.html
http://xmlspecificationcompare.codeplex.com/
https://github.com/netbike/netbike.xmlunit
This code doesn't satisfy all your requirements, but it's simple and I'm using for my unit tests. Attribute order doesn't matter, but element order does. Element inner text is not compared. I also ignored case when comparing attributes, but you can easily remove that.
public bool XMLCompare(XElement primary, XElement secondary)
{
if (primary.HasAttributes) {
if (primary.Attributes().Count() != secondary.Attributes().Count())
return false;
foreach (XAttribute attr in primary.Attributes()) {
if (secondary.Attribute(attr.Name.LocalName) == null)
return false;
if (attr.Value.ToLower() != secondary.Attribute(attr.Name.LocalName).Value.ToLower())
return false;
}
}
if (primary.HasElements) {
if (primary.Elements().Count() != secondary.Elements().Count())
return false;
for (var i = 0; i <= primary.Elements().Count() - 1; i++) {
if (XMLCompare(primary.Elements().Skip(i).Take(1).Single(), secondary.Elements().Skip(i).Take(1).Single()) == false)
return false;
}
}
return true;
}
try XMLUnit. This library is available for both Java and .Net
For comparing two XML outputs in automated testing I found XNode.DeepEquals.
Compares the values of two nodes, including the values of all descendant nodes.
Usage:
var xDoc1 = XDocument.Parse(xmlString1);
var xDoc2 = XDocument.Parse(xmlString2);
bool isSame = XNode.DeepEquals(xDoc1.Document, xDoc2.Document);
//Assert.IsTrue(isSame);
Reference: https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xnode.deepequals?view=netcore-2.2
Comparing XML documents is complicated. Google for xmldiff (there's even a Microsoft solution) for some tools. I've solved this a couple of ways. I used XSLT to sort elements and attributes (because sometimes they would appear in a different order, and I didn't care about that), and filter out attributes I didn't want to compare, and then either used the XML::Diff or XML::SemanticDiff perl module, or pretty printed each document with every element and attribute on a separate line, and using Unix command line diff on the results.
https://github.com/CameronWills/FatAntelope
Another alternative library to the Microsoft XML Diff API. It has a XML diffing algorithm to do an unordered comparison of two XML documents and produce an optimal matching.
It is a C# port of the X-Diff algorithm described here:
http://pages.cs.wisc.edu/~yuanwang/xdiff.html
Disclaimer: I wrote it :)
Another way to do this would be -
Get the contents of both files into two different strings.
Transform the strings using an XSLT (which will just copy everything over to two new strings). This will ensure that all spaces outside the elements are removed. This will result it two new strings.
Now, just compare the two strings with each other.
This won't give you the exact location of the difference, but if you just want to know if there is a difference, this is easy to do without any third party libraries.
I am using ExamXML for comparing XML files. You can try it.
The authors, A7Soft, also provide API for comparing XML files
Not relevant for the OP since it currently ignores child order, but if you want a code only solution you can try XmlSpecificationCompare which I somewhat misguidedly developed.
All above answers are helpful but I tried XMLUnit which look's easy to use Nuget package to check difference between two XML files, here is C# sample code
public static bool CheckXMLDifference(string xmlInput, string xmlOutput)
{
Diff myDiff = DiffBuilder.Compare(Input.FromString(xmlInput))
.WithTest(Input.FromString(xmlOutput))
.CheckForSimilar().CheckForIdentical()
.IgnoreComments()
.IgnoreWhitespace().NormalizeWhitespace().Build();
if(myDiff.Differences.Count() == 0)
{
// when there is no difference
// files are identical, return true;
return true;
}
else
{
//return false when there is 1 or more difference in file
return false;
}
}
If anyone want's to test it, I have also created online tool using it, you can take a look here
https://www.minify-beautify.com/online-xml-difference
Based #Two Cents answer and using this link XMLSorting i have created my own XmlComparer
Compare XML program
private static bool compareXML(XmlNode node, XmlNode comparenode)
{
if (node.Value != comparenode.Value)
return false;
if (node.Attributes.Count>0)
{
foreach (XmlAttribute parentnodeattribute in node.Attributes)
{
string parentattributename = parentnodeattribute.Name;
string parentattributevalue = parentnodeattribute.Value;
if (parentattributevalue != comparenode.Attributes[parentattributename].Value)
{
return false;
}
}
}
if(node.HasChildNodes)
{
sortXML(comparenode);
if (node.ChildNodes.Count != comparenode.ChildNodes.Count)
return false;
for(int i=0; i<node.ChildNodes.Count;i++)
{
string name = node.ChildNodes[i].LocalName;
if (compareXML(node.ChildNodes[i], comparenode.ChildNodes[i]) == false)
return false;
}
}
return true;
}
Sort XML program
private static void sortXML(XmlNode documentElement)
{
int i = 1;
SortAttributes(documentElement.Attributes);
SortElements(documentElement);
foreach (XmlNode childNode in documentElement.ChildNodes)
{
sortXML(childNode);
}
}
private static void SortElements(XmlNode rootNode)
{
for(int j = 0; j < rootNode.ChildNodes.Count; j++) {
for (int i = 1; i < rootNode.ChildNodes.Count; i++)
{
if (String.Compare(rootNode.ChildNodes[i].Name, rootNode.ChildNodes[1 - 1].Name) < 0)
{
rootNode.InsertBefore(rootNode.ChildNodes[i], rootNode.ChildNodes[i - 1]);
}
}
}
// Console.WriteLine(j++);
}
private static void SortAttributes(XmlAttributeCollection attribCol)
{
if (attribCol == null)
return;
bool changed = true;
while (changed)
{
changed = false;
for (int i = 1; i < attribCol.Count; i++)
{
if (String.Compare(attribCol[i].Name, attribCol[i - 1].Name) < 0)
{
//Replace
attribCol.InsertBefore(attribCol[i], attribCol[i - 1]);
changed = true;
}
}
}
}
I solved this problem of xml comparison using XSLT 1.0 which can be used for comparing large xml files using an unordered tree comparison algorithm.
https://github.com/sflynn1812/xslt-diff-turbo