c# - Sum method extension for IEnumerable<TimeSpan> -


edit: sorry confusion concerning names of variables. totalhours , hours indeed timespans , i'm trying sum timespans, not hours property of timespan.

i'm using sum hours column(of type timespan) in table:

totalhours = maingridtable.select(x => x.hours).aggregate((x,y) => x.add(y)); 

i've tried making sum extension ienumerable doesn't work:

public static timespan sum<tsource>(this ienumerable<tsource> source, func<tsource, timespan> selector)  {                 return source.aggregate(((t1, t2) => t1.add(t2));          } 

i've searched .net source code , found existing sum methods returned as:

return enumerable.sum(enumerable.select(source, selector)); 

i tried making non-generic sum extension enumerable this, not getting recognized above return statement , keeps asking decimal argument.

    public static timespan sum(this ienumerable<timespan> source) {         timespan sum = new timespan(0, 0, 0);         foreach (timespan v in source) {             if (v != null) sum.add(v);         }         return sum;     } 

i'm not versed in funcs, extensions , generics. mistake , how can make work?

edit clarifying you're trying achieve. i'm still not sure got it, last attempt @ :-)

    public static timespan sum<tsource>(this ienumerable<tsource> source,           func<tsource, timespan> selector)      {         var ts = new timespan();         return source.aggregate(ts, (current, entry) => current + selector(entry));     } 

i'm not sure try indicate totalhours, because obviously, sum of multiple time spans (that include hours, minutes, days, seconds, etc. each) expressed total hours else, summing hours property of timespans. decided, meant summing full instances - can access required totalhours, etc. information resulting timespan.

timespan immutable, datetime, common gotcha is, need use result of add method.

public static timespan sum(this ienumerable<timespan> source) {     timespan sum = new timespan(0, 0, 0);     foreach (timespan v in source) {         sum = sum.add(v);     }     return sum; } 

also note, timespan value type (struct), can never null. check against null in code superflous.

the linq version this:

    public static timespan sum(this ienumerable<timespan> source)     {         timespan sum = new timespan(0, 0, 0);         return source.aggregate(sum, (current, v) => current.add(v));     } 

again, need use result of add method.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -