using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class PropertyDiff
{
public int Index { get; set; }
public string PropertyName { get; set; }
public object Value1 { get; set; }
public object Value2 { get; set; }
}
public static class ListObjectComparer
{
public static List<PropertyDiff> CompareAllProperties<T>(IList<T> list1, IList<T> list2)
{
var diffs = new List<PropertyDiff>();
if (list1 == null && list2 == null)
{
return diffs;
}
if (list1 == null || list2 == null)
{
diffs.Add(new PropertyDiff
{
Index = -1,
PropertyName = "List",
Value1 = list1,
Value2 = list2
});
return diffs;
}
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead)
.ToArray();
int maxCount = Math.Max(list1.Count, list2.Count);
for (int i = 0; i < maxCount; i++)
{
if (i >= list1.Count)
{
diffs.Add(new PropertyDiff
{
Index = i,
PropertyName = "Item",
Value1 = null,
Value2 = list2[i]
});
continue;
}
if (i >= list2.Count)
{
diffs.Add(new PropertyDiff
{
Index = i,
PropertyName = "Item",
Value1 = list1[i],
Value2 = null
});
continue;
}
var item1 = list1[i];
var item2 = list2[i];
if (item1 == null && item2 == null)
{
continue;
}
if (item1 == null || item2 == null)
{
diffs.Add(new PropertyDiff
{
Index = i,
PropertyName = "Item",
Value1 = item1,
Value2 = item2
});
continue;
}
foreach (var property in properties)
{
object value1 = property.GetValue(item1);
object value2 = property.GetValue(item2);
if (!Equals(value1, value2))
{
diffs.Add(new PropertyDiff
{
Index = i,
PropertyName = property.Name,
Value1 = value1,
Value2 = value2
});
}
}
}
return diffs;
}
}
foreach (var diff in diffs)
{
Console.WriteLine(
$"Index={diff.Index}, Property={diff.PropertyName}, Value1={diff.Value1}, Value2={diff.Value2}");
}