none
can i create a view from a datatable using a "group by" RRS feed

  • Question

  • I have a datatable with 6 column. I want to create a dataview that includes only 3 column and does a group by on those columns. Is there a direct way to achieve this ?

    1. I know i can do this manually
    2. I've found some dataset helper classes out there that let you do that but it seems like they are from vs 2003 days and i was wondering if there are direct ways to do this.

    Thanks

    Wednesday, June 3, 2009 6:27 PM

Answers

  • So long as you do not want an "editable" view, you can use a LINQ query.

                DataSet ds = new DataSet();
                DataTable dt = ds.Tables.Add("Test");
                dt.Columns.Add("a");
                dt.Columns.Add("b");
                dt.Columns.Add("c");
                dt.Columns.Add("d");
                dt.Columns.Add("amt", typeof(decimal));
                dt.Rows.Add("1", "2", "3", "4", 17.21m);
                dt.Rows.Add("1", "2", "3", "5", 15.75m);
                dt.Rows.Add("6", "7", "8", "9", 19.95m);
    
                var q = (from r in dt.AsEnumerable()
                         group r by new { a = r.Field<string>("a"), b = r.Field<string>("b"), c = r.Field<string>("c") } into grps
                         select new { a = grps.Key.a, b = grps.Key.b, totalamt = grps.Sum(x => x.Field<decimal>("amt")) });
    
                dataGridView1.DataSource = q.ToArray();  
    Wednesday, June 3, 2009 11:42 PM

All replies

  • So long as you do not want an "editable" view, you can use a LINQ query.

                DataSet ds = new DataSet();
                DataTable dt = ds.Tables.Add("Test");
                dt.Columns.Add("a");
                dt.Columns.Add("b");
                dt.Columns.Add("c");
                dt.Columns.Add("d");
                dt.Columns.Add("amt", typeof(decimal));
                dt.Rows.Add("1", "2", "3", "4", 17.21m);
                dt.Rows.Add("1", "2", "3", "5", 15.75m);
                dt.Rows.Add("6", "7", "8", "9", 19.95m);
    
                var q = (from r in dt.AsEnumerable()
                         group r by new { a = r.Field<string>("a"), b = r.Field<string>("b"), c = r.Field<string>("c") } into grps
                         select new { a = grps.Key.a, b = grps.Key.b, totalamt = grps.Sum(x => x.Field<decimal>("amt")) });
    
                dataGridView1.DataSource = q.ToArray();  
    Wednesday, June 3, 2009 11:42 PM
  • Just as a note, the linq query that BinaryCoder is doing will not be a 2way bindable view.

    Thanks
    Chris Robinson
    Program Manager - DataSet
    This posting is provided "AS IS" with no warranties, and confers no rights.
    Friday, June 5, 2009 1:42 AM