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

相关推荐
狂人开飞机14 小时前
14、游戏手感与视觉打磨
游戏·游戏引擎·godot
狂人开飞机20 小时前
15、音频系统
游戏引擎·godot
狂人开飞机20 小时前
16、粒子线条与视觉特效
游戏引擎·godot
心前阳光1 天前
Unity发布PC软件图标不能改变
unity·游戏引擎
an86950012 天前
unity如何在visual studio中打断点debug
unity·游戏引擎·visual studio
xcLeigh2 天前
Unity基础:使用Transform控制物体移动——Translate与position详解
unity·游戏引擎
FairGuard手游加固2 天前
Unity小游戏加密:global-metadata.dat与AssetBundle保护
游戏·unity·游戏引擎
狂人开飞机2 天前
11、UI系统
游戏引擎·godot
真鬼1232 天前
【Unity AI】Untiy链接cursor与MCP
unity·游戏引擎
WarPigs2 天前
Unity设置人物位置无效的原因
unity