List 的 Diff 功能

文章介绍了IListComparer接口和ListCompareData类,用于在两个列表间执行添加(Add)和删除(Sub)操作,通过id和整型比较项确定新增和减少的内容。
摘要由CSDN通过智能技术生成

    public interface IListComparer
    {
        bool Contain<T>(T t) where T: ListCompareData;
    }
    public class ListCompareData : IListComparer
    {
        public int mId;
        public int mCompareId;

        public bool Contain<T>(T t) where T : ListCompareData
        {
            return (mId == t.mId && mCompareId == t.mCompareId);
        }
    }

    public static List<T> Diff<T>(this List<T> rList1, List<T> rList2, EListDiffType rDiffType) where T : ListCompareData
    {
        List<T> resultList = new List<T>();
        ///新增的数据, 2有1没有
        if (rDiffType == EListDiffType.Add)
        {
            foreach (T item2 in rList2)
            {
                bool isNew = true;
                foreach(T item1 in rList1)
                {
                    if (item1.Contain(item2))
                    {
                        isNew = false;
                        break;
                    }
                }
                if (isNew) resultList.Add(item2);
            }
        }
        //减少的数据,1有2没有
        else if (rDiffType == EListDiffType.Sub)
        {
            foreach (T item1 in rList1)
            {
                bool isRemoved = true;
                foreach (T item2 in rList2)
                {
                    if (item1.Contain(item2))
                    {
                        isRemoved = false;
                        break;  
                    }
                }
                if(isRemoved) resultList.Add(item1);
            }
        }
        return resultList;
    }
}

使用: 

列表新增的内容:

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

列表减少的内容:

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

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值