Distinct with custom comparer
Trying to use Distinct()
using a custom comparer and it gives me the error:
cannot be inferred from the usage. Try specifying the type arguments explicitly
The Default
comparer works fine but doesn't give the results I expect of course. How can I fix this?
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.Empl开发者_如何学JAVAoyeeID.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());
}
The type of groupedData
is some IEnumerable<{an anonymous type}>
whereas MyRowComparer
is IEqualityComparer<TimeEntryValidation>
It's unclear whether you intended listItems
to be a list of groups, or whether you wanted the actual items themselves.
If it's the latter, you probably want something like this:
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>
}
精彩评论