0

Hi basically i wanted to group my datatable by the department column, i want to load the results back into another datatable through looping but it keeps giving me an error, im not sure how to group a datatable with linq and load it into another datatable other than looping

here is my code

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

another linq query i tried

               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"));
                    }
6
  • Do you want to add all possible departments in separate table? Commented Jun 14, 2019 at 1:53
  • @GaurangDave Dont think so no, i just want a datatable of the departments because the first datatable which i am querying against consists duplicate departments
    – wren
    Commented Jun 14, 2019 at 2:01
  • I think that is what I told. You want a separate datatable with all departments in it. Now question is do you want duplicates or distinct? Commented Jun 14, 2019 at 2:03
  • @GaurangDave oh yes its i want to load the results of the query in a seperate datatable, distinct departments
    – wren
    Commented Jun 14, 2019 at 2:04
  • No need to group in that case. Try var query1 = dtClone.AsEnumerable().Select(row => row.Field<string>("department")).Distinct(); Commented Jun 14, 2019 at 2:07

1 Answer 1

0

No need to group data in case of getting distinct records (only one column).

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

ORDER BY

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.