Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c # using linq to group by multiple columns in a datatable

I have three columns in a datatable: string, DateTime, and decimal. I want to group by the string and decimal column, and for the rows grouped I want to sum the decimal values. I know how to do the sum part, but how do you group two different columns in a datatable?

This is my code so far which doesn't work properly:

var newSort = from row in objectTable.AsEnumerable()
              group row by new {ID = row.Field<string>("resource_name"), time1 = row.Field<DateTime>("day_date")} into grp
              orderby grp.Key
              select new
              {
                 resource_name1 = grp.Key.ID,
                 day_date1 = grp.Key.time1,
                 Sum = grp.Sum(r => r.Field<Decimal>("actual_hrs"))
              };
like image 504
Sam Avatar asked Jul 01 '11 17:07

Sam


2 Answers

I don't think you're giving us the full story. Other than orderby not working with anonymous types (the code you gave wouldn't have compiled), your query should work the way you want. I just put this in LINQPad:

var objectTable = new DataTable();
objectTable.Columns.Add("resource_name",typeof(string));
objectTable.Columns.Add("day_date",typeof(DateTime));
objectTable.Columns.Add("actual_hrs",typeof(decimal));
objectTable.Rows.Add(1, DateTime.Today, 1);
objectTable.Rows.Add(2, DateTime.Today, 2);

var newSort = from row in objectTable.AsEnumerable()
            group row by new {ID = row.Field<string>("resource_name"), time1 = row.Field<DateTime>("day_date")} into grp
            select new
                {
                    resource_name1 = grp.Key.ID,
                    day_date1 = grp.Key.time1,
                    Sum = grp.Sum(r => r.Field<Decimal>("actual_hrs"))
                };
newSort.Dump();

... and I got these results:

resource_name1 | day_date1            | Sum
1              | 7/1/2011 12:00:00 AM | 1 
2              | 7/1/2011 12:00:00 AM | 2 
like image 98
StriplingWarrior Avatar answered Oct 22 '22 04:10

StriplingWarrior


use this code

var newSort = from row in objectTable.AsEnumerable()
          group row by new {ID = row.Field<string>("resource_name"), time1 =    row.Field<DateTime>("day_date")} into grp
          orderby grp.Key
          select new
          {
             resource_name1 = grp.Key.ID,
             day_date1 = grp.Key.time1,
             Sum = grp.Sum(r => Convert.ToDecimal(r.ItemArray[2]))
          };
like image 29
ar.gorgin Avatar answered Oct 22 '22 05:10

ar.gorgin