我的数据表中返回的数据如下所示:


  部门|员工姓名
  
  1 |员工1
  
  1 |员工1
  
  2 |员工2
  
  3 |员工3
  
  3 |员工3
  
  3 |员工3


我试图只获取不同的行并将其放入集合中,如下所示:

IEnumerable<Department> departments = dt.AsEnumerable().Select(row =>
    new Department
        {
            DepartmentID = Int32.Parse(row["DepartmentID"].ToString()),
            Employee = new Employee { EmployeeName = row["EmployeeName"].ToString() }
        }).Distinct();


它应该只返回3行,而是返回全部6行。

我在这里做错了什么?

最佳答案

不确定,但下列其中一种可能对您有用........

只是这样做

var distrows= table1.AsEnumerable().Distinct();


将完成您的任务..........比创建distrow部门集合更重要。

IEnumerable<Department> departments = (from DataRow dRow in distrows
                         new Department
        {
            DepartmentID = Int32.Parse(row["DepartmentID"].ToString()),
            Employee = new Employee { EmployeeName = row["EmployeeName"].ToString() }
        });


要么

var distinctRows = (from DataRow dRow in dTable.Rows
            select new {col1=dRow["dataColumn1"],col2=dRow["dataColumn2"]}).Distinct();


IEnumerable<Department> departments = (from DataRow dRow in distrows
                             new Department
            {
                DepartmentID = Int32.Parse(distinctRows.col1),
                Employee = new Employee { EmployeeName = distinctRows.col2.ToString() }
            });

09-06 00:18