Mehrdad
Mehrdad

Reputation: 2116

Get differences between two list

I have a 2 lists of an object type:

List<MyClass> list1;
List<MyClass> list2;

What is the best way (performance and clean code) to extract differences in data between these two List?
I mean get objects that is added, deleted, or changed (and the change)?

Upvotes: 2

Views: 12227

Answers (5)

Muneeb Zulfiqar
Muneeb Zulfiqar

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

w.b
w.b

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

David.Chu.ca
David.Chu.ca

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

Darren
Darren

Reputation: 70728

IEnumerable<string> differenceQuery = list1.Except(list2);

http://msdn.microsoft.com/en-us/library/bb397894.aspx

Upvotes: 2

Mathew Thompson
Mathew Thompson

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

Related Questions