假设我们的一个List的数据序列化后是这样的:
[ { "Id": 766, "UserId": 6, "GameId": 1, "Content": "AAAAAAAAAAA" }, { "Id": 780, "UserId": 125, "GameId": 28, "Content": "BBBBBBBBBBBB" }, { "Id": 779, "UserId": 6, "GameId": 1, "Content": "CCCCCCCCCCCCC" }, { "Id": 779, "UserId": 6, "GameId": 1, "Content": "CCCCCCCCCCCCC" } ]
一般情况下,在List中使用Distinct可以去掉重List里面的重复的元素,但由于 Distinct 默认比较的是List对象的引用,当数据为上面的JSON的这种情况下,Distinct去重后还是原来的数据
如果我们想根据对象里面的某个字段(比如Id)进行去重来返回唯一记录,我们可以这样做:
新建一个比较器类(对Distinct新增一个扩展方法)
public class CommonEqualityComparer: IEqualityComparer { private Func keySelector; public CommonEqualityComparer(Func keySelector) { this.keySelector = keySelector; } public bool Equals(T x, T y) { return EqualityComparer .Default.Equals(keySelector(x), keySelector(y)); } public int GetHashCode(T obj) { return EqualityComparer .Default.GetHashCode(keySelector(obj)); } } public static class DistinctExtensions { public static IEnumerable Distinct (this IEnumerable source, Func keySelector) { return source.Distinct(new CommonEqualityComparer (keySelector)); } }
然后只需
List=List.Distinct(p=>p.Id).ToList();
即可完成根据Id值去重筛选