对比两个同类型的泛型集合并返回差异泛型集合 ——两个List<类名>的比较

时间:2023-04-20 20:04:56
 1:  /// <summary>
   2:  /// 对比两个同类型的泛型集合并返回差异泛型集合
   3:  /// </summary>
   4:  /// <typeparam name="T">泛型类型</typeparam>
   5:  /// <param name="newModel">修改后的数据集合</param>
   6:  /// <param name="oldModel">原始数据集合</param>
   7:  /// <returns>返回与原始集合有差异的集合</returns>
   8:  public static List<T> GetModiflyList<T>(List<T> newModel, List<T> oldModel)
   9:  {
  10:      List<T> list = new List<T>();
  11:      foreach (T newMod in newModel)
  12:      {
  13:          bool IsExist = false;
  14:          foreach (T oldMol in oldModel)
  15:          {
  16:              //取得老实体对象的属性集合
  17:              PropertyInfo[] pi = oldMol.GetType().GetProperties();
  18:              //定义记数器
  19:              int i = 0;
  20:   
  21:              //将老实体对象的没一个属性值和新实体对象进行循环比较
  22:              foreach (PropertyInfo p in pi)
  23:              {
  24:                  //防止object.Equals时实例化对象发生异常
  25:                  object o_new = newMod.GetType().GetProperty(p.Name).GetValue(newMod, null);
  26:                  if (o_new == null)
  27:                      o_new = (object)String.Empty;
  28:   
  29:                  //防止object.Equals时实例化对象发生异常
  30:                  object o_old = p.GetValue(oldMol, null);
  31:                  Type type = o_old.GetType();
  32:                  if (type.Name == "ExtensionDataObject")
  33:                  {
  34:                      i++;
  35:                  }
  36:                  if (o_old == null)
  37:                      o_old = (object)String.Empty;
  38:   
  39:                  //新老实体比较并记录成功次数
  40:                  if (object.Equals(o_new, o_old))
  41:                  {
  42:                      i++;
  43:                  }
  44:                  //若成功次数和属性数目相等则说明已经存在或者没有发生过修改条出循环
  45:                  if (i == pi.Length)
  46:                  {
  47:                      IsExist = true;
  48:                      break;
  49:                  }
  50:              }
  51:   
  52:              //没有发生过修改条出循环
  53:              if (IsExist)
  54:                  break;
  55:          }
  56:   
  57:          //如果不存在则添加该实体到List<T>中
  58:          if (!IsExist)
  59:              list.Add(newMod);
  60:   
  61:      }
  62:      return list;
  63:  }