List 的 Diff 功能

cs 复制代码
    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 和 一个整形比较

相关推荐
晓13133 小时前
【Cocos Creator 3.x】篇——第二章 入门
前端·javascript·游戏引擎
玖玥拾5 小时前
Cocos学习笔记:粒子系统与对象层批量处理
游戏引擎·cocos2d
是果果呀儿6 小时前
Vuforia实现物体旋转、移动、缩放
unity·增强现实
不知名的老吴9 小时前
Unity3D 2022安装教程及全流程下载步骤指南
unity·游戏引擎
Thomas_YXQ9 小时前
Unity3D Addressable 深度优化热更性能消耗
开发语言·3d·unity·微信
程序员也有头发9 小时前
如何使用AI工具开发Unity
unity·游戏引擎·ai编程
隔窗听雨眠10 小时前
从零开始的游戏开发入门指南
unity
sinat_3845031110 小时前
【无标题】
unity·webgl
caimouse10 小时前
Godot 引擎官方常见问题(FAQ)整理
游戏引擎·godot
一锅炖出任易仙11 小时前
创梦汤锅学习日记day29
学习·ai·ue5·游戏引擎