C#查找两个通用列表之间的更改

时间:2019-06-19 15:40:01

标签: c# .net generics

比较两个通用列表以查找更改集时遇到问题,因为更改的影响会传播到多个目标:

问题是:

  • 它们不是简单的类型(我必须使用比较器
  • 我需要知道更改(添加和删除的项目)
  • 我必须创建一个可用的解决方案

例如:-

假设您要旅行,并且想要打开更新屏幕以添加或删除即将来临的学生。但是,仅更新列表是不够的,因为您要查找新添加或删除的学生并向其父母发送电子邮件:

经过一些搜索和思考,我开发了一种通用的扩展方法,该方法对我有很大帮助...在下面找到它

1 个答案:

答案 0 :(得分:-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);
    }

该解决方案的另一个重要补充是通用比较器。

/// <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();
    }
}

用法示例:

var (added, removed) = tripobject.Students.Difference(newtripObject.Students, new IdEqualityComparer<Student>());