创建一个不同的iqueryable列表

时间:2011-12-12 22:27:16

标签: c# datetime iequalitycomparer

我有一个对象列表,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();

2 个答案:

答案 0 :(得分:2)

return AllStudents.Where(s => s.IsLastActionRemoved)
                  .Distinct(new GroupStudentStatusComparer())
                  .OrderByDescending(d => d.LastActionDate)
                  .ToList();

答案 1 :(得分:0)

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结束。