我使用linq

时间:2019-06-14 01:48:11

标签: c# linq

您好,基本上我想按部门列对数据表进行分组,我想通过循环将结果加载回另一个数据表中,但它一直给我一个错误,我不确定如何将数据表与linq分组并将其加载到除了循环之外的另一个数据表

这是我的代码

                DataTable data = new DataTable();
                data.Columns.Add("Department");

                var query1 = dtClone.AsEnumerable().GroupBy(row => row.Field<string>("department"));
                if (query1.Any())
                   foreach(DataRow dr in query1)//here
                    {
                        DataRow newrow = data.Rows.Add();
                        newrow.SetField("Department", dr.Field<string>("department"));
                    }

                foreach (DataRow row in data.Rows)
                    MessageBox.Show(row[0].ToString());

我尝试过的另一个linq查询

               DataTable data = new DataTable();
                data.Columns.Add("Department");
                var query1 = from r in dtClone.AsEnumerable()
                             orderby r.Field<string>("department") ascending
                             group r by r.Field<string>("department") into r
                             select r;
                if (query1.Any())
                   foreach(DataRow dr in query1)
                    {
                        DataRow newrow = data.Rows.Add();
                        newrow.SetField("Department", dr.Field<string>("department"));
                    }

1 个答案:

答案 0 :(得分:0)

如果获得不同的记录(仅一列),则无需对数据进行分组。

var query1 = dtClone.AsEnumerable().Select(row => row.Field<string>("department")).Distinct();

订购

var query1 = dtClone.AsEnumerable().Select(row => row.Field<string>("department")).Distinct().OrderBy(s => s);