Skip to content

Instantly share code, notes, and snippets.

@pingkunga
Created March 12, 2024 08:03
Show Gist options
  • Save pingkunga/59f3e3db3930f0ff5c402b1e84c318d0 to your computer and use it in GitHub Desktop.
Save pingkunga/59f3e3db3930f0ff5c402b1e84c318d0 to your computer and use it in GitHub Desktop.
dotnet DeepEqualsExtensions
public static bool DeepEquals (this object obj, object another)
{
if (ReferenceEquals (obj, another)) return true;
if ((obj == null) || (another == null)) return false;
if (obj.GetType ()! = another.GetType ()) return false;
// If the property is not a class, just int, double, DateTime, etc. v
// Call regular equal function
if (! obj.GetType (). IsClass) return obj.Equals (another);
var result = true;
foreach (var property in obj.GetType (). GetProperties ())
{
var objValue = property.GetValue (obj);
var anotherValue = property.GetValue (another);
// Continue recursion
if (! objValue.DeepEquals (anotherValue)) result = false;
}
return result;
}
public static bool DeepEquals <T> (this IEnumerable <T> obj, IEnumerable <T> another)
{
if (ReferenceEquals (obj, another)) return true;
if ((obj == null) || (another == null)) return false;
bool result = true;
// Browse each element in 2 given list
using (IEnumerator <T> enumerator1 = obj.GetEnumerator ())
using (IEnumerator <T> enumerator2 = another.GetEnumerator ())
{
while (true)
{
bool hasNext1 = enumerator1.MoveNext ();
bool hasNext2 = enumerator2.MoveNext ();
// If there is 1 list, or 2 different elements, exit the loop
if (hasNext1! = hasNext2 ||! enumerator1.Current.DeepEquals (enumerator2.Current))
{
result = false;
break;
}
// Stop the loop when 2 lists are all
if (! hasNext1) break;
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment