得到DataTable中使用LINQ不同项目 [英] Get distinct items from DataTable using LINQ

查看:93
本文介绍了得到DataTable中使用LINQ不同项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个DataTable,看起来像要返回的数据:

I have data being returned in a DataTable that looks like:

系| EmployeeName

Department | EmployeeName

1 | Employee1

1 | Employee1

1 | Employee1

1 | Employee1

2 |和Employee2

2 | Employee2

3 | Employee3

3 | Employee3

3 | Employee3

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();

它应该只返回3行,而是它返回所有6个。

It should only return 3 rows, but instead it's returning all 6.

我在做什么错在这里?

推荐答案

不知道,但下列情况之一可能为你工作..........

Not sure but one of the following may work for you ..........

只是这样做

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() }
            });

这篇关于得到DataTable中使用LINQ不同项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆