问题描述
data_list.Sum(p=>变量);可以这样做吗?
解决方案
解决方案二:
data_list.Sum(p=>p.变量);
解决方案三:
除非你的p本身就是数值类型对象publicstaticdecimal?Sum(thisIEnumerable<decimal?>source);publicstaticdecimalSum(thisIEnumerable<decimal>source);publicstaticdouble?Sum(thisIEnumerable<double?>source);publicstaticdoubleSum(thisIEnumerable<double>source);publicstaticfloat?Sum(thisIEnumerable<float?>source);publicstaticfloatSum(thisIEnumerable<float>source);publicstaticint?Sum(thisIEnumerable<int?>source);publicstaticintSum(thisIEnumerable<int>source);publicstaticlong?Sum(thisIEnumerable<long?>source);publicstaticlongSum(thisIEnumerable<long>source);publicstaticdecimal?Sum<TSource>(thisIEnumerable<TSource>source,Func<TSource,decimal?>selector);publicstaticdecimalSum<TSource>(thisIEnumerable<TSource>source,Func<TSource,decimal>selector);publicstaticdouble?Sum<TSource>(thisIEnumerable<TSource>source,Func<TSource,double?>selector);publicstaticdoubleSum<TSource>(thisIEnumerable<TSource>source,Func<TSource,double>selector);publicstaticfloat?Sum<TSource>(thisIEnumerable<TSource>source,Func<TSource,float?>selector);publicstaticfloatSum<TSource>(thisIEnumerable<TSource>source,Func<TSource,float>selector);publicstaticint?Sum<TSource>(thisIEnumerable<TSource>source,Func<TSource,int?>selector);publicstaticintSum<TSource>(thisIEnumerable<TSource>source,Func<TSource,int>selector);publicstaticlong?Sum<TSource>(thisIEnumerable<TSource>source,Func<TSource,long?>selector);publicstaticlongSum<TSource>(thisIEnumerable<TSource>source,Func<TSource,long>selector);这是Sum的所有重载
解决方案四:
可以啊,除了变量类型要正确外,基本没问题了List<int>l=newList<int>(){3,4,6};intp=100;varq=l.Sum(x=>p);Console.WriteLine(q);
解决方案五:
数值类型可以,如果是自定义类型,可以考虑重载下sum函数
解决方案六:
引用3楼hanjun0612的回复:
可以啊,除了变量类型要正确外,基本没问题了List<int>l=newList<int>(){3,4,6};intp=100;varq=l.Sum(x=>p);Console.WriteLine(q);
求和直接l.Sum()就可以了varlist=newList<int>(newint[]{1,2,3,4,5,6,7});//就和Console.WriteLine(list.Sum());Console.WriteLine(list.Sum(s=>s));//求奇数和Console.WriteLine(list.Where(w=>w%2==1).Sum());Console.WriteLine(list.Sum(s=>(s%2==1)?s:0));