版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36361038/article/details/83062706
今天在做项目的时候遇到从数据库中查询数据之后又重复的数据,展示在页面中需要的的是不重复的数据,所以就从网上找了看了下谢了这样的对象去重方法,结合Linq使用:
根据对象 中的属性进行比较去重:
public class StuCompare : IEqualityComparer<View_FBase_StuClassPlanInfo>
{
public bool Equals(View_FBase_StuClassPlanInfo x, View_FBase_StuClassPlanInfo y)
{
if (x == null || y == null)
return false;
if (x.TeachingDepartmentName == y.TeachingDepartmentName && x.MajorName == y.MajorName && x.Grade==y.Grade)
return true;
else
return false;
}
public int GetHashCode(View_FBase_StuClassPlanInfo obj)
{
if (obj == null)
return 0;
else
return obj.TeachingDepartmentName.GetHashCode() ^ obj.MajorName.GetHashCode() ^ obj.Grade.GetHashCode();
}
}
写好方法后,使用如下:
//根据对象中 的不同属性去重
List<View_FBase_StuClassPlanInfo> items =list.Distinct(new StuCompare()).ToList();
这样就得想要的数据。
注意上面的
if (x.TeachingDepartmentName == y.TeachingDepartmentName && x.MajorName == y.MajorName && x.Grade==y.Grade)
这里面是对象中的属性,这儿是对象三个属性进行比较,同理,三个以上一样。