创建不同的可查询列表
本文关键字:查询 列表 创建 | 更新日期: 2023-09-27 18:17:51
我有一个对象列表,GroupStudentStatus,我需要区分它。我写了下面的类来做到这一点。
相关的 2 个属性是 GroupStudentStatus.IsLastActionRemoved(DateTime( 和 GroupStudentStatus.Student.Guid。
protected List<GroupStudentStatus> RemovedStudents
{
get
{
return AllStudents.Where(s => s.IsLastActionRemoved).Distinct().OrderByDescending(d => d.LastActionDate).ToList();
}
}
public class GroupStudentStatusComparer : IEqualityComparer<GroupStudentStatus>
{
public GroupStudentStatus Compare(GroupStudentStatus x, GroupStudentStatus y)
{
//get the student that was last removed
if (!Equals(x, y))
{
return x.LastActionDate > y.LastActionDate ? x : y;
}
return x;
}
public bool Equals(GroupStudentStatus x, GroupStudentStatus y)
{
return x.Student.Guid.Equals(y.Student.Guid);
}
public int GetHashCode(GroupStudentStatus obj)
{
return obj.Student.Guid.GetHashCode();
}
}
我认为这是正确的,除了我不知道如何测试它。
我试图这样做:
return AllStudents.Where(s => s.IsLastActionRemoved)
.Distinct(new GroupStudentStatusComparer((x, y) => x.Compare(x,y)))
.OrderByDescending(d => d.LastActionDate).ToList();
return AllStudents.Where(s => s.IsLastActionRemoved)
.Distinct(new GroupStudentStatusComparer())
.OrderByDescending(d => d.LastActionDate)
.ToList();
return AllStudents.Where(s => s.IsLastActionRemoved).GroupBy(gss => gss.Student).Select(g => new GroupStudentStatus(g.Key, g.Select(gss2 => gss2.LastActionDate).Max(), true)).OrderByDescending(d => d.LastActionDate).ToList();
最终使用了 groupBy。