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 和 一个整形比较

相关推荐
SmalBox4 小时前
【渲染流水线】[逐片元阶段]-[裁剪测试]以UnityURP为例
unity·渲染
与火星的孩子对话7 小时前
Unity高级开发:反射原理深入解析与实践指南 C#
java·unity·c#·游戏引擎·lucene·反射
scoone9 小时前
开源游戏引擎Bevy 和 Godot
游戏引擎·godot
阿赵3D10 小时前
Unity2022打包安卓报错的奇葩问题
android·unity·安卓
霸王•吕布10 小时前
游戏引擎中的粒子系统
游戏引擎·粒子系统·粒子发射盒·粒子物理参数·粒子实例·粒子生命周期·粒子参数
小徐小徐编程不急19 小时前
unity实现背包拖拽排序
unity·游戏引擎
萘柰奈1 天前
Unity进阶--C#补充知识点--【Unity跨平台的原理】Mono与IL2CPP
unity·c#·游戏引擎
淡海水1 天前
【原理】Unity GC 对比 C# GC
unity·c#·gc·垃圾回收
阿赵3D1 天前
Unity引擎播放HLS自适应码率流媒体视频
unity·游戏引擎·音视频·流媒体·hls
NRatel1 天前
Unity 游戏提升 Android TargetVersion 相关记录
android·游戏·unity·提升版本