当前位置:   article > 正文

List 的 Diff 功能

List 的 Diff 功能

  1. public interface IListComparer
  2. {
  3. bool Contain<T>(T t) where T: ListCompareData;
  4. }
  5. public class ListCompareData : IListComparer
  6. {
  7. public int mId;
  8. public int mCompareId;
  9. public bool Contain<T>(T t) where T : ListCompareData
  10. {
  11. return (mId == t.mId && mCompareId == t.mCompareId);
  12. }
  13. }
  14. public static List<T> Diff<T>(this List<T> rList1, List<T> rList2, EListDiffType rDiffType) where T : ListCompareData
  15. {
  16. List<T> resultList = new List<T>();
  17. ///新增的数据, 2有1没有
  18. if (rDiffType == EListDiffType.Add)
  19. {
  20. foreach (T item2 in rList2)
  21. {
  22. bool isNew = true;
  23. foreach(T item1 in rList1)
  24. {
  25. if (item1.Contain(item2))
  26. {
  27. isNew = false;
  28. break;
  29. }
  30. }
  31. if (isNew) resultList.Add(item2);
  32. }
  33. }
  34. //减少的数据,1有2没有
  35. else if (rDiffType == EListDiffType.Sub)
  36. {
  37. foreach (T item1 in rList1)
  38. {
  39. bool isRemoved = true;
  40. foreach (T item2 in rList2)
  41. {
  42. if (item1.Contain(item2))
  43. {
  44. isRemoved = false;
  45. break;
  46. }
  47. }
  48. if(isRemoved) resultList.Add(item1);
  49. }
  50. }
  51. return resultList;
  52. }
  53. }

使用: 

列表新增的内容:

var newEquips = list1.Diff<ListCompareData>(list2, Util.EListDiffType.Add);

列表减少的内容:

 var oldEquips = list1.Diff<ListCompareData>(list2, Util.EListDiffType.Sub);

可以自行扩展ListCompareData的比较项,这里是使用了id 和 一个整形比较

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/306288
推荐阅读
相关标签
  

闽ICP备14008679号