Cannot get sum from Dataview list

eric.bryan

Member
Joined
Jun 15, 2014
Messages
8
Programming Experience
3-5
Hello everybody,

I try to get a list from a dataview containing a sum and grouped by some fields.


C#:
DataView view = _objManager.ACCOUNTS.DefaultView;
                        
                        // Set RowStateFilter to display the current rows.
                        view.RowStateFilter = DataViewRowState.CurrentRows;

                        var res = ((DataTable)view.Table)
                          .AsEnumerable()
                          .GroupBy(row => new { ID = row.Field<long?>("ID"), ELEM = row.Field<string>("ELEM") })
                          .Select(sel => new
                          {
                              NAME = sel.First()["NAME"],
                              ID = sel.First()["ID"],
                              IBAN = sel.First()["IBAN"],
                              BIC = sel.First()["BIC"],
                              INFO = sel.First()["INFO"],
                  AMOUNT= sel.Sum(s => sel.Sum()["AMOUNT"])  //doesn't work                           
                          }).ToList();
But the sum doesn't compile.
Do you have and idea ?
Thanks a lot in advance.
Eric
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,130
Location
Sydney, Australia
Programming Experience
10+
First things first, why are you starting with a DataTable, getting it's DefaultView and then getting the Table from that? That just takes you back to the same DataTable you started with. Instead of doing this:
DataView view = _objManager.ACCOUNTS.DefaultView;
and then using this:
((DataTable)view.Table).AsEnumerable()
just use this:
_objManager.ACCOUNTS.AsEnumerable()
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,130
Location
Sydney, Australia
Programming Experience
10+
I think that this:
AMOUNT= sel.Sum(s => sel.Sum()["AMOUNT"]
should be this:
AMOUNT= sel.Sum(row => row.Field<decimal>("AMOUNT")
Remember that sel is a group of DataRow objects so you're calling Sum to sum the AMOUNT fields of the rows in that group. You can obviously change decimal to a different type if appropriate.
 
Top Bottom