与自定义比较器不同

本文关键字:比较器 自定义 | 更新日期: 2023-09-27 17:50:25

尝试使用自定义比较器Distinct(),它给了我错误:

不能从用法中推断出来。尝试显式指定类型参数

Default比较器工作良好,但没有给出我期望的结果。我该如何解决这个问题?

public class TimeEntryValidation
{
    public string EmployeeID { get; set; }
    public string EmployeeLocation { get; set; }
    public string EmployeeDepartment { get; set; }
    public int RowIndex { get; set; }
}
public class MyRowComparer : IEqualityComparer<TimeEntryValidation>
{
    public bool Equals(TimeEntryValidation x, TimeEntryValidation y)
    {
        return (x.EmployeeDepartment == y.EmployeeDepartment && x.EmployeeLocation == y.EmployeeLocation);
    }
    public int GetHashCode(TimeEntryValidation obj)
    {
        return obj.EmployeeID.GetHashCode(); 
    }
}
void Query(List<TimeEntryValidation> listToQuery)
{
    var groupedData =
        from oneValid in listToQuery
        group oneValid by oneValid.EmployeeID
            into g
        where g.Count() > 1
        select new {DoubleItems = g};
    var listItems = groupedData.Distinct(new MyRowComparer());
}

与自定义比较器不同

groupedData的类型是某些IEnumerable<{an anonymous type}>MyRowComparer的类型是IEqualityComparer<TimeEntryValidation>

不清楚您是否打算将listItems作为组的列表,或者您是否想要实际的项目本身。

如果是后者,您可能需要这样做:

void Query(List<TimeEntryValidation> listToQuery)
{
    var groupedData = from oneValid in listToQuery
                        group oneValid by oneValid.EmployeeID
                            into g
                            where g.Count() > 1
                            select  g ;
    var listItems = groupedData.SelectMany(group => group).Distinct(new MyRowComparer());
    //listItems is now an IEnumerable<TimeEntryValidation>
}