1

I have a list of objects, GroupStudentStatus, that I need to make distinct. I wrote the class below to do this.
The 2 attributes that are relevant are GroupStudentStatus.IsLastActionRemoved (DateTime) and 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();
    }


}

I think this is right, except I can't figure out how to test it.

I was trying to do this:

return AllStudents.Where(s => s.IsLastActionRemoved)
                  .Distinct(new GroupStudentStatusComparer((x, y) => x.Compare(x,y)))
                  .OrderByDescending(d => d.LastActionDate).ToList();
Surjit Samra
  • 4,614
  • 1
  • 26
  • 36
Brad8118
  • 4,672
  • 11
  • 36
  • 48

2 Answers2

2
return AllStudents.Where(s => s.IsLastActionRemoved)
                  .Distinct(new GroupStudentStatusComparer())
                  .OrderByDescending(d => d.LastActionDate)
                  .ToList();
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
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();

Ended up using groupBy.

Brad8118
  • 4,672
  • 11
  • 36
  • 48