使用 GroupBy
更新的新解决方案:
实际上有一个更简单的解决方案:
IList<Project> projects = (from update in dbContext.TicketUpdates where update.TicketUpdatesEmployeeID == Profile.EmployeeID)
.GroupBy(tu=>tu.Ticket.Project)
.Select(group=>group.First())
.OrderByDescending(tu=>tu.TicketUpdatesEndDate)
.Select(tu=>tu.Ticket.Project)
.ToList();
(我刚刚看到,在我写这篇文章的时候,其他人也发布了类似的答案)
使用自定义 IEqualityComparer 的旧解决方案(我不确定这是否适用于 linq2sql)
有一个采用自定义 IEqualityComparer 的 Distinct 重载。因此,在投影数据之前,请使用自定义 IEqualityComparer 对 TicketUpdates 进行 Distinct 。
IEqualityComparer 应该将所有 TicketUpdates 视为相等,如果它们具有相同的项目。这样,具有相同项目的 TicketUpdates 将被丢弃。
(请注意,您无法控制将丢弃哪些具有相同项目的 TicketUpdates。因此,如果具有相同项目的这些 TicketUpdates 具有不同的 EndDates,则您需要一个涉及 GroupBy 的解决方案。
IList<Project> projects = (from update in dbContext.TicketUpdates where update.TicketUpdatesEmployeeID == Profile.EmployeeID)
.Distinct(new ProjectComparer())
.OrderByDescending(tu=>tu.TicketUpdatesEndDate)
.Select(tu=>tu.Ticket.Project)
.ToList();
// Your comparer should look somewhat like this
// (untested code! And I do not know all the details about your class structure)
class ProjectComparer : IEqualityComparer<TicketUpdates>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(TicketUpdates x, TicketUpdates y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether projects are equal.
//(perhaps do a null check for Ticket!)
return x.Ticket.Project== y.Ticket.Project;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(TicketUpdates x)
{
//Check whether the object is null
if (Object.ReferenceEquals(x, null)) return 0;
// null check for Ticket and Project?
return x.Ticket.Project.GetHashCode();
}
}