Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking two lists for Modifications

I have got two lists of two different type which has the following common properties.

Id -->used to identify corresponding objects

Bunch of other Properties

ModificationDate

Need to compare these two lists based on Modification date.If the modified date is different (first list ModificationDate greater than second list's ModificationDate then, copy all the properties if that item from first list to second.

Please let me know the best way to do this.

EDITED:Second list may or maynot contain all elements of the first and vice versa.My first list is always the source list. so if an item is present in list 1 and not present in list 2 we need to add it in list 2. also if an item present in list 2 but in not in list 1 then remove it from list2.

like image 812
Ashley John Avatar asked Dec 31 '25 11:12

Ashley John


2 Answers

Finding added/deleted items

var list1 = new List<MyType>();
var list2 = new List<MyType>();

// These two assume MyType : IEquatable<MyType>
var added = list1.Except(list2);
var deleted = list2.Except(list1);

// Now add "added" to list2, remove "deleted" from list2

If MyType does not implement IEquatable<MyType>, or the implementation is not based solely on comparing ids, you will need to create an IEqualityComparer<MyType>:

class MyTypeIdComparer : IEqualityComparer<MyType>
{
    public bool Equals(MyType x, MyType y)
    {
        return x.Id.CompareTo(y.Id);
    }

    public int GetHashCode(MyType obj)
    {
        return obj.Id.GetHashCode();
    }
}

Which will allow you to do:

// This does not assume so much for MyType
var comparer = new MyTypeIdComparer();
var added = list1.Except(list2, comparer);
var deleted = list2.Except(list1, comparer);

Finding modified items

var modified = list1.Concat(list2)
                    .GroupBy(item => item.Id)
                    .Where(g => g.Select(item => item.ModificationDate)
                                 .Distinct().Count() != 1);

// To propagate the modifications:
foreach(var grp in modified) {
    var items = grp.OrderBy(item => item.ModificationDate);
    var target = items.First(); // earliest modification date = old
    var source = grp.Last();    // latest modification date = new

    // And now copy properties from source to target
}
like image 83
Jon Avatar answered Jan 05 '26 02:01

Jon


This might be able to help. The Linq library has lots of decent functions, such as Except, Intersection.

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

like image 40
Glenit Avatar answered Jan 05 '26 00:01

Glenit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!