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