LINQ怎么根据“某个字段”去除重复数据查询(急求答案)
1个回答
展开全部
Distinct方法的第二重载可以
Enumerable.Distinct<TSource> (IEnumerable<TSource>, IEqualityComparer<TSource>),
例如数据类为
class School
{
public int Id { get; set; }
public string Name { get; set; }
//是否重点学校
public bool IsKeySchool { get; set; }
}
实现IEqualityComparer<School>的比较器类为
class SchoolComparer : EqualityComparer<School>
{
public override bool Equals(School x, School y)
{
return x.IsKeySchool==y.IsKeySchool;
}
public override int GetHashCode(School obj)
{
return obj.IsKeySchool.GetHashCode();
}
}
原始列表为
var schoolList = new List<School> {
new School{Id=1, Name="三中",IsKeySchool=true},
new School{Id=2, Name="五中",IsKeySchool=true},
new School{Id=3, Name="十中",IsKeySchool=false},
new School{Id=4, Name="十五中",IsKeySchool=true},
new School{Id=5, Name="二十中",IsKeySchool=false},
};
执行
var tempList = schoolList.Distinct(new SchoolComparer());
结果就只有两条“三中”和“十中”
Enumerable.Distinct<TSource> (IEnumerable<TSource>, IEqualityComparer<TSource>),
例如数据类为
class School
{
public int Id { get; set; }
public string Name { get; set; }
//是否重点学校
public bool IsKeySchool { get; set; }
}
实现IEqualityComparer<School>的比较器类为
class SchoolComparer : EqualityComparer<School>
{
public override bool Equals(School x, School y)
{
return x.IsKeySchool==y.IsKeySchool;
}
public override int GetHashCode(School obj)
{
return obj.IsKeySchool.GetHashCode();
}
}
原始列表为
var schoolList = new List<School> {
new School{Id=1, Name="三中",IsKeySchool=true},
new School{Id=2, Name="五中",IsKeySchool=true},
new School{Id=3, Name="十中",IsKeySchool=false},
new School{Id=4, Name="十五中",IsKeySchool=true},
new School{Id=5, Name="二十中",IsKeySchool=false},
};
执行
var tempList = schoolList.Distinct(new SchoolComparer());
结果就只有两条“三中”和“十中”
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询