c# - Calculate sum of column using group by in Linq -


i have list structure :

public class factor     {         public datetime? date { set; get; }         public string innovoiceid { set; get; }         public string explain { set; get; }         public string tax { set; get; }         public string transport { set; get; }         public int64? bedehkar { set; get; }         public int64? bestankar { set; get; }         public int64? mande { set; get; }     }          list<factor> factors = new list<factor>(); 

i created query groups records based on innovoiceid .and calculate sum of tax , sum of transport , bedehkar , bestankar , mande.

my query is:

  list<factor> factorsortlist =            factors.orderby(o => o.date)                   .tolist()                   .groupby(i => i.innovoiceid)                   .select(g => new { tax = g.sum(i => convert.toint32(i.tax)), transport = g.sum(i => convert.toint32(i.transport)), bedehkar = g.sum(i => i.bedehkar), bestankar = g.sum(i => i.bestankar), mande = g.sum(i => i.mande) }); 

but got error:

   cannot implicitly convert type 'system.collections.generic.ienumerable<anonymoustype#1>' 'system.collections.generic.list<samtaapplication.bulayer.payment.reportpayment.factor>'. explicit conversion exists (are missing cast?) 

you're creating anonymous type

.select(g => new { ... }); 

and pretending it's factor

list<factor> factorsortlist = ... 

you'll need use var since it's anonymous type or create different type in select statement.

the following 1 way resolve fact 2 of sum variables string , not numeric (assuming int, may desire here instead double.

var factorsortlist =        factors.orderby(o => o.date)               .tolist()               .groupby(i => i.innovoiceid)               .select(g => new { tax = g.sum(i => convert.toint32(i.tax)), transport = g.sum(i => convert.toint32(i.transport)), bedehkar = g.sum(i => i.bedehkar), bestankar = g.sum(i => i.bestankar), mande = g.sum(i => i.mande) }); 

or if aggregated type here meant factor...

              .select(g => new factor() { tax = g.sum(i => convert.toint32(i.tax)).tostring(), transport = g.sum(i => convert.toint32(i.transport)).tostring(), bedehkar = g.sum(i => i.bedehkar), bestankar = g.sum(i => i.bestankar), mande = g.sum(i => i.mande) }).tolist(); 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -