嘗試使用自定義比較使用Distinct()
,它給我的錯誤:DISTINCT與自定義比較
cannot be inferred from the usage. Try specifying the type arguments explicitly
的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());
}
不是錯誤的原因,但...因爲'Equals'的結果你比較器壞了,'GetHashCode'方法無關。任何兩個相同*的項必須*具有相同的哈希碼;這不一定是使用比較器的情況。 – LukeH 2011-04-18 22:22:49