-4

I had a problem with comparing two generic lists to find the set of changes because the effect of change propagates to multiple destinations:

The Problems was:

  • They are not simple types (I have to use comparer
  • I need to know the changes (Added and Removed Items)
  • I have to create a usable solution

Ex:-

Assume you have a trip and you want to open the update screen to add or remove the coming students. However, a simple list update is not enough since you want to find the students that are newly added or removed and send an e-mail to their parents:

Some search and thinking, I have developed a generic Extension Method that Helped me much... Find it below

Walid Hanafy
  • 1,429
  • 2
  • 14
  • 26

1 Answers1

-1
    /// <summary>
    /// A Function to compute the difference between two lists and returns the added and removed items
    ///  Removed = Old - New
    ///  Added = New - Old
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list">Old List</param>
    /// <param name="otherList">New List</param>
    /// <returns>Named Tuple of Added and Removed Items</returns>
    public static (List<T> added,List<T> removed) Difference<T>(this List<T> list, List<T> otherList,IEqualityComparer<T> comparer)
    {
        var removed = list.Except(otherList, comparer).ToList();
        var added = otherList.Except(list, comparer).ToList();
        return  (added:added,removed:removed);
    }

Another Important Addition to the solution is the generic comparer.

/// <summary>
/// A generic Comparer depends on the Assumption that both types have an Id property
/// </summary>
/// <typeparam name="T"></typeparam>
public class IdEqualityComparer<T> : IEqualityComparer<T>
{
    public bool Equals(T Item1, T Item2)
    {
        if (Item2 == null && Item1 == null)
            return true;
        else if (Item1 == null || Item2 == null)
            return false;
        var id1 = Item1.GetType().GetProperty("Id").GetValue(Item1, null).ToString();
        var id2 = Item2.GetType().GetProperty("Id").GetValue(Item2, null).ToString();
        if (id1==id2)
            return true;
        else
            return false;
    }

    public int GetHashCode(T Item)
    {
        var id = Item.GetType().GetProperty("Id").GetValue(Item, null).ToString();
        return id.GetHashCode();
    }
}

Usage Sample:

var (added, removed) = tripobject.Students.Difference(newtripObject.Students, new IdEqualityComparer<Student>());
Walid Hanafy
  • 1,429
  • 2
  • 14
  • 26