2011-04-18 125 views
1

嘗試使用自定義比較使用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()); 
} 
+0

不是錯誤的原因,但...因爲'Equals'的結果你比較器壞了,'GetHashCode'方法無關。任何兩個相同*的項必須*具有相同的哈希碼;這不一定是使用比較器的情況。 – LukeH 2011-04-18 22:22:49

回答

1

類型的groupedData一些IEnumerable<{an anonymous type}>MyRowComparerIEqualityComparer<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> 
} 
+0

我想要的是實際的物品,而不是團體。 – mgf 2011-04-19 22:59:50

+0

關於LukeH關於GetHashCode()的評論 - 我應該返回obj.ToString()。GetHashCode(),我的Equal比我在這裏發佈的要複雜一些。感謝你們兩位 - LukeH和Davy8,非常感謝。 – mgf 2011-04-19 23:04:52