I have data being returned in a DataTable that looks like:
Department | EmployeeName
1 | Employee1
1 | Employee1
2 | Employee2
3 | Employee3
3 | Employee3
3 | Employee3
I'm trying to get only distinct rows and put it into a collection, like so:
IEnumerable<Department> departments = dt.AsEnumerable().Select(row =>
new Department
{
DepartmentID = Int32.Parse(row["DepartmentID"].ToString()),
Employee = new Employee { EmployeeName = row["EmployeeName"].ToString() }
}).Distinct();
It should only return 3 rows, but instead it's returning all 6.
What am I doing wrong here?
what i think the problem here is that you are creating different objects with have no implementation for comparing the equality based on some propertiese. so the
Distinct()
method compares the refference of the objects and hence concludes that all the objects are different because they point to different reffrences.what you shoud do instead is try parsing the information in an object that implements
IEqualityComparer
and then use.Select(<IEqualityComparer>).Distinct()
Class/Schema
DataTable and Records
Query
Not sure but one of the following may work for you ..........
just do this
will do your task..........than create collection of department form the
distrow
..OR