Reputation: 2116
I have a 2 lists of an object type:
List<MyClass> list1;
List<MyClass> list2;
Upvotes: 2
Views: 12227
Reputation: 1023
Try this for objects comparison and loop around it for List<T>
public static void GetPropertyChanges<T>(this T oldObj, T newObj)
{
Type type = typeof(T);
foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
object selfValue = type.GetProperty(pi.Name).GetValue(oldObj, null);
object toValue = type.GetProperty(pi.Name).GetValue(newObj, null);
if (selfValue != null && toValue != null)
{
if (selfValue.ToString() != toValue.ToString())
{
//do your code
}
}
}
}
Upvotes: 0
Reputation: 11228
One way to get items that are either in list1 or in list2 but not in both would be:
var common = list1.Intersect(list2);
var exceptions = list1.Except(common).Concat(list2.Except(common));
Upvotes: 0
Reputation: 38644
You may use FindAll
to get the result you want, even you don't have IEquatable
or IComparable
implemented in your MyClass
. Here is one example:
List<MyClass> interetedList = list1.FindAll(delegate(MyClass item1) {
MyClass found = list2.Find(delegate(MyClass item2) {
return item2.propertyA == item1.propertyA ...;
}
return found != null;
});
In the same way, you can get your interested items from list2
by comparing to list1
.
This strategy may get your "changed" items as well.
Upvotes: 0
Reputation: 70728
IEnumerable<string> differenceQuery = list1.Except(list2);
http://msdn.microsoft.com/en-us/library/bb397894.aspx
Upvotes: 2
Reputation: 56429
Try Except
with Union
, but you'll need to do it for both in order to find differences in both.
var exceptions = list1.Except(list2).Union(list2.Except(list1)).ToList();
OR as a Linq alternative, there could be a much faster approach: HashSet.SymmetricExceptWith():
var exceptions = new HashSet(list1);
exceptions.SymmetricExceptWith(list2);
Upvotes: 13