我在DataTable中返回的数据如下所示:
部门| EmployeeName
1 | Employee1
1 | Employee1
2 |和Employee2
3 | Employee3
3 | Employee3
3 | Employee3
我正在尝试只获取不同的行并将其放入集合中,如下所示:
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行。
我在这里做错了什么?
答案 0 :(得分:3)
不确定,但以下其中一项可能对您有用..........
就这样做
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() }
});
答案 1 :(得分:0)
<强>类/模式强>
public class abc
{
public int id;
}
DataTable和记录
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("id", Type.GetType("System.Int32"));
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr["id"] = 1;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["id"] = 1;
dt.Rows.Add(dr);
<强>查询强>
var qa = dt.AsEnumerable()
.Select(row => new
{
Id = row.Field<int>("id"),
})
.Distinct();
答案 2 :(得分:0)
我认为这里的问题是你正在创建不同的对象,没有实现比较基于某些属性的相等性。所以Distinct()
方法比较对象的引用,因此得出结论,所有对象都是不同的,因为它们指向不同的reffrence。
你要做的是尝试解析实现IEqualityComparer
的对象中的信息,然后使用.Select(<IEqualityComparer>).Distinct()